package handlers

import (
	"errors"
	"strconv"
	"strings"

	"github.com/gofiber/fiber/v2"

	otherperson "wucher/internal/domain/other_person"
	"wucher/internal/shared/pkg/apperrorsx"
	"wucher/internal/shared/pkg/uuidv7"
	requestdto "wucher/internal/transport/http/dto/request"
	responsedto "wucher/internal/transport/http/dto/response"
	"wucher/internal/transport/http/response"
)

// OtherPersonHandler serves the reusable, non-staff "other person" master (a picker for
// takeover other-people). It never mixes with contacts/staff.
type OtherPersonHandler struct {
	svc otherperson.Service
}

func NewOtherPersonHandler(svc otherperson.Service) *OtherPersonHandler {
	return &OtherPersonHandler{svc: svc}
}

func otherPersonResource(p *otherperson.OtherPerson) responsedto.OtherPersonResource {
	return responsedto.OtherPersonResource{
		Type: "other_person",
		ID:   idString(p.ID),
		Attributes: responsedto.OtherPersonAttributes{
			Name:        p.Name,
			MobilePhone: p.MobilePhone,
			Email:       p.Email,
		},
	}
}

// writeOtherPersonError maps service/domain errors to the right HTTP status.
func writeOtherPersonError(c *fiber.Ctx, err error) error {
	switch {
	case errors.Is(err, otherperson.ErrNameRequired):
		return apperrorsx.Write(c, apperrorsx.New(apperrorsx.ErrValidation).WithCause(err))
	case errors.Is(err, otherperson.ErrDuplicate):
		return apperrorsx.Write(c, apperrorsx.New(apperrorsx.ErrBusinessRuleFailed).WithCause(err))
	case errors.Is(err, otherperson.ErrNotFound):
		return apperrorsx.Write(c, apperrorsx.New(apperrorsx.ErrDataNotFound).WithCause(err))
	default:
		return apperrorsx.Write(c, apperrorsx.New(apperrorsx.ErrInternal).WithCause(err))
	}
}

// Search godoc
// @Summary Search reusable "other people" (non-staff) for the takeover picker
// @Description Lists master other-people whose name/mobile_phone/email matches `q` (empty `q` = most recent). Pick one and pass its id as `other_person_id` in a takeover's other_person to reuse without re-entering the data.
// @Tags Contact - Other People
// @Produce json
// @Param q query string false "Search text (name / mobile_phone / email)"
// @Param limit query int false "Max results (default 20)"
// @Param offset query int false "Offset"
// @Success 200 {object} responsedto.OtherPersonListResponse
// @Router /api/v1/contact/other [get]
func (h *OtherPersonHandler) Search(c *fiber.Ctx) error {
	q := strings.TrimSpace(c.Query("q"))
	limit, _ := strconv.Atoi(c.Query("limit"))
	offset, _ := strconv.Atoi(c.Query("offset"))
	rows, total, err := h.svc.Search(c.UserContext(), q, limit, offset)
	if err != nil {
		return apperrorsx.Write(c, apperrorsx.New(apperrorsx.ErrInternal).WithCause(err))
	}
	data := make([]responsedto.OtherPersonResource, 0, len(rows))
	for i := range rows {
		data = append(data, otherPersonResource(&rows[i]))
	}
	return response.WriteWithMeta(c, fiber.StatusOK, data, map[string]any{"total": total})
}

// Get godoc
// @Summary Get one reusable "other person"
// @Tags Contact - Other People
// @Produce json
// @Param id path string true "Other person id"
// @Success 200 {object} responsedto.OtherPersonResponse
// @Router /api/v1/contact/other/get/{id} [get]
func (h *OtherPersonHandler) Get(c *fiber.Ctx) error {
	id, err := uuidv7.ParseString(strings.TrimSpace(c.Params("id")))
	if err != nil {
		return apperrorsx.Write(c, apperrorsx.New(apperrorsx.ErrInvalidRequest).WithCause(err))
	}
	row, err := h.svc.GetByID(c.UserContext(), id)
	if err != nil {
		return apperrorsx.Write(c, apperrorsx.New(apperrorsx.ErrInternal).WithCause(err))
	}
	if row == nil {
		return apperrorsx.Write(c, apperrorsx.New(apperrorsx.ErrDataNotFound))
	}
	return response.Write(c, fiber.StatusOK, otherPersonResource(row))
}

// Create godoc
// @Summary Create a reusable "other person" (non-staff)
// @Description Registers a person in the other-people master so it can be reused across takeovers. The (name, mobile_phone, email) identity must be unique.
// @Tags Contact - Other People
// @Accept json
// @Produce json
// @Param request body requestdto.OtherPersonRequest true "Other person"
// @Success 201 {object} responsedto.OtherPersonResponse
// @Router /api/v1/contact/other/create [post]
func (h *OtherPersonHandler) Create(c *fiber.Ctx) error {
	var req requestdto.OtherPersonRequest
	if err := c.BodyParser(&req); err != nil {
		return writeBodyParseError(c, err, apperrorsx.ErrInvalidRequest)
	}
	actor := actorUserID(c)
	p := &otherperson.OtherPerson{
		Name:        req.Data.Attributes.Name,
		MobilePhone: req.Data.Attributes.MobilePhone,
		Email:       req.Data.Attributes.Email,
		CreatedBy:   actor,
		UpdatedBy:   actor,
	}
	if err := h.svc.Create(c.UserContext(), p); err != nil {
		return writeOtherPersonError(c, err)
	}
	return response.Write(c, fiber.StatusCreated, otherPersonResource(p))
}

// Update godoc
// @Summary Update a reusable "other person"
// @Description Replaces the name/mobile_phone/email of a master person. The new identity must not collide with another person.
// @Tags Contact - Other People
// @Accept json
// @Produce json
// @Param id path string true "Other person id"
// @Param request body requestdto.OtherPersonRequest true "Other person"
// @Success 200 {object} responsedto.OtherPersonResponse
// @Router /api/v1/contact/other/update/{id} [patch]
func (h *OtherPersonHandler) Update(c *fiber.Ctx) error {
	id, err := uuidv7.ParseString(strings.TrimSpace(c.Params("id")))
	if err != nil {
		return apperrorsx.Write(c, apperrorsx.New(apperrorsx.ErrInvalidRequest).WithCause(err))
	}
	var req requestdto.OtherPersonRequest
	if err := c.BodyParser(&req); err != nil {
		return writeBodyParseError(c, err, apperrorsx.ErrInvalidRequest)
	}
	p := &otherperson.OtherPerson{
		ID:          id,
		Name:        req.Data.Attributes.Name,
		MobilePhone: req.Data.Attributes.MobilePhone,
		Email:       req.Data.Attributes.Email,
		UpdatedBy:   actorUserID(c),
	}
	if err := h.svc.Update(c.UserContext(), p); err != nil {
		return writeOtherPersonError(c, err)
	}
	row, err := h.svc.GetByID(c.UserContext(), id)
	if err != nil {
		return apperrorsx.Write(c, apperrorsx.New(apperrorsx.ErrInternal).WithCause(err))
	}
	if row == nil {
		return apperrorsx.Write(c, apperrorsx.New(apperrorsx.ErrDataNotFound))
	}
	return response.Write(c, fiber.StatusOK, otherPersonResource(row))
}

// Delete godoc
// @Summary Delete a reusable "other person"
// @Description Soft-deletes a master person. Existing takeover snapshots keep their own copy of the data.
// @Tags Contact - Other People
// @Produce json
// @Param id path string true "Other person id"
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/contact/other/delete/{id} [delete]
func (h *OtherPersonHandler) Delete(c *fiber.Ctx) error {
	id, err := uuidv7.ParseString(strings.TrimSpace(c.Params("id")))
	if err != nil {
		return apperrorsx.Write(c, apperrorsx.New(apperrorsx.ErrInvalidRequest).WithCause(err))
	}
	if err := h.svc.Delete(c.UserContext(), id, actorUserID(c)); err != nil {
		return writeOtherPersonError(c, err)
	}
	return response.Write(c, fiber.StatusOK, map[string]any{"id": idString(id), "deleted": true})
}
