package handlers

import (
	"errors"
	"strconv"
	"strings"
	"time"

	"github.com/gofiber/fiber/v2"
	"gorm.io/gorm"

	"wucher/internal/domain/vocation"
	"wucher/internal/shared/pkg/apperrors"
	"wucher/internal/shared/pkg/apperrorsx"
	"wucher/internal/shared/pkg/uuidv7"
	"wucher/internal/transport/http/dto"
	"wucher/internal/transport/http/jsonapi"
	"wucher/internal/transport/http/response"
	"wucher/internal/transport/http/validators"
)

type VocationHandler struct {
	svc      vocation.Service
	validate *validators.Validator
}

func NewVocationHandler(svc vocation.Service) *VocationHandler {
	return &VocationHandler{
		svc:      svc,
		validate: validators.New(),
	}
}

// CreateVocation godoc
// @Summary Create vocation
// @Description Create a vocation row.
// @Tags OPC - Vocation
// @Accept json
// @Produce json
// @Param request body dto.VocationCreateRequest true "JSON:API vocation create request"
// @Success 201 {object} dto.VocationResponse
// @Failure 422 {object} dto.ErrorResponse
// @Failure 400 {object} dto.ErrorResponse
// @Router /api/v1/vocation/create [post]
func (h *VocationHandler) Create(c *fiber.Ctx) error {
	var req dto.VocationCreateRequest
	if err := c.BodyParser(&req); err != nil {
		return writeVocationErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "Invalid JSON",
			Detail: safeInternalDetail(),
		}})
	}
	if errs := h.validate.ValidateStruct(req); errs != nil {
		return writeVocationErrors(c, fiber.StatusUnprocessableEntity, errs)
	}

	name := strings.TrimSpace(req.Data.Attributes.Name)
	if name == "" {
		return writeVocationErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "name is required",
			Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/name"},
		}})
	}

	row := &vocation.Vocation{
		Name:      name,
		SortKey:   cloneIntPointer(req.Data.Attributes.SortKey),
		Note:      strings.TrimSpace(stringOrDefault(req.Data.Attributes.Note, "")),
		IsActive:  boolOrDefault(req.Data.Attributes.IsActive, true),
		CreatedBy: actorUserID(c),
		UpdatedBy: actorUserID(c),
	}

	if err := h.svc.Create(c.UserContext(), row); err != nil {
		return writeVocationErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "Create failed",
			Detail: safeInternalDetail(),
		}})
	}

	created, err := h.svc.GetByID(c.UserContext(), row.ID)
	if err == nil && created != nil {
		return response.Write(c, fiber.StatusCreated, vocationResource(created))
	}
	return response.Write(c, fiber.StatusCreated, vocationResource(row))
}

// UpdateVocation godoc
// @Summary Update vocation (partial)
// @Description Patch vocation by ID.
// @Tags OPC - Vocation
// @Accept json
// @Produce json
// @Param uuid path string true "Vocation UUID (UUIDv7)"
// @Param request body dto.VocationUpdateRequest true "JSON:API vocation update request"
// @Success 200 {object} dto.VocationResponse
// @Failure 422 {object} dto.ErrorResponse
// @Failure 404 {object} dto.ErrorResponse
// @Router /api/v1/vocation/update/{uuid} [patch]
func (h *VocationHandler) Update(c *fiber.Ctx) error {
	uuidStr := c.Params("uuid")
	id, err := uuidv7.ParseString(uuidStr)
	if err != nil {
		return writeVocationErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "uuid is invalid UUID",
			Source: &jsonapi.ErrorSource{Pointer: "/path/uuid"},
		}})
	}

	var req dto.VocationUpdateRequest
	if err := c.BodyParser(&req); err != nil {
		return writeVocationErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "Invalid JSON",
			Detail: safeInternalDetail(),
		}})
	}
	if errs := h.validate.ValidateStruct(req); errs != nil {
		return writeVocationErrors(c, fiber.StatusUnprocessableEntity, errs)
	}

	if strings.TrimSpace(req.Data.ID) == "" {
		return writeVocationErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "id is required",
			Source: &jsonapi.ErrorSource{Pointer: "/data/id"},
		}})
	}
	if req.Data.ID != uuidStr {
		return writeVocationErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "id does not match path uuid",
			Source: &jsonapi.ErrorSource{Pointer: "/data/id"},
		}})
	}

	attrs := req.Data.Attributes
	if attrs.Name == nil && !attrs.SortKey.Set && attrs.Note == nil && attrs.IsActive == nil {
		return writeVocationErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "at least one attribute must be provided",
			Source: &jsonapi.ErrorSource{Pointer: "/data/attributes"},
		}})
	}

	existing, err := h.svc.GetByID(c.UserContext(), id)
	if err != nil || existing == nil {
		return writeVocationErrors(c, fiber.StatusNotFound, []jsonapi.ErrorObject{{
			Status: "404",
			Title:  "Not found",
			Detail: "vocation not found",
		}})
	}

	if attrs.Name != nil {
		v := strings.TrimSpace(*attrs.Name)
		if v == "" {
			return writeVocationErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
				Status: "422",
				Title:  "Validation error",
				Detail: "name cannot be empty",
				Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/name"},
			}})
		}
		existing.Name = v
	}
	if attrs.SortKey.Set {
		if attrs.SortKey.Valid {
			sortKey := attrs.SortKey.Value
			existing.SortKey = &sortKey
		} else {
			existing.SortKey = nil
		}
	}
	if attrs.Note != nil {
		existing.Note = strings.TrimSpace(*attrs.Note)
	}
	if attrs.IsActive != nil {
		existing.IsActive = *attrs.IsActive
	}
	existing.UpdatedBy = actorUserID(c)

	if err := h.svc.Update(c.UserContext(), existing); err != nil {
		return writeVocationErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "Update failed",
			Detail: safeInternalDetail(),
		}})
	}

	updated, err := h.svc.GetByID(c.UserContext(), existing.ID)
	if err == nil && updated != nil {
		return response.Write(c, fiber.StatusOK, vocationResource(updated))
	}
	return response.Write(c, fiber.StatusOK, vocationResource(existing))
}

// DeleteVocation godoc
// @Summary Delete vocation
// @Tags OPC - Vocation
// @Produce json
// @Param uuid path string true "Vocation UUID (UUIDv7)"
// @Success 200 {object} dto.GenericDeleteResponse
// @Failure 404 {object} dto.ErrorResponse
// @Router /api/v1/vocation/delete/{uuid} [delete]
func (h *VocationHandler) Delete(c *fiber.Ctx) error {
	uuidStr := c.Params("uuid")
	id, err := uuidv7.ParseString(uuidStr)
	if err != nil {
		return writeVocationErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "uuid is invalid UUID",
			Source: &jsonapi.ErrorSource{Pointer: "/path/uuid"},
		}})
	}

	if err := h.svc.Delete(c.UserContext(), id, actorUserID(c)); err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return writeVocationErrors(c, fiber.StatusNotFound, []jsonapi.ErrorObject{{Status: "404", Title: "Not found", Detail: "vocation not found"}})
		}
		if _, ok := apperrors.AsDeleteConflict(err); ok {
			return writeVocationErrors(c, fiber.StatusConflict, []jsonapi.ErrorObject{{Status: "409", Title: "Conflict", Detail: safeInternalDetail()}})
		}
		return writeVocationErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{Status: "400", Title: "Delete failed", Detail: safeInternalDetail()}})
	}

	return response.Write(c, fiber.StatusOK, jsonapi.Resource{
		Type: "vocation_delete",
		Attributes: map[string]any{
			"deleted": true,
		},
	})
}

// ListVocation godoc
// @Summary List vocation
// @Description JSON:API list with pagination, filtering and sorting. Sort values: name, -name, sortkey, -sortkey, note, -note, is_active, -is_active, created_at, -created_at, updated_at, -updated_at.
// @Tags OPC - Vocation
// @Produce json
// @Param filter[search] query string false "Search by name/note"
// @Param page[number] query int false "Page number (default 1)"
// @Param page[size] query int false "Page size (default 20, max 100)"
// @Param sort query string false "Sort order"
// @Success 200 {object} dto.VocationListResponse
// @Router /api/v1/vocation/get-all [get]
func (h *VocationHandler) List(c *fiber.Ctx) error {
	filter := c.Query("filter[search]")
	if filter == "" {
		filter = c.Query("filter[name]")
	}
	if filter == "" {
		filter = c.Query("search")
	}

	pageNumber := parseIntDefault(c.Query("page[number]"), 0)
	if pageNumber <= 0 {
		pageNumber = parseIntDefault(c.Query("page"), 1)
	}

	pageSize := parseIntDefault(c.Query("page[size]"), 0)
	if pageSize <= 0 {
		pageSize = parseIntDefault(c.Query("limit"), 0)
	}
	if pageSize <= 0 {
		pageSize = parseIntDefault(c.Query("size"), 20)
	}
	if pageSize > 100 {
		pageSize = 100
	}
	if pageSize < 1 {
		pageSize = 20
	}
	if pageNumber < 1 {
		pageNumber = 1
	}

	offset := (pageNumber - 1) * pageSize
	_ = offset
	sort := c.Query("sort")

	rows, total, err := h.svc.List(c.UserContext(), filter, sort, 0, 0)
	if err != nil {
		return writeVocationErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "List failed",
			Detail: safeInternalDetail(),
		}})
	}

	data := make([]dto.VocationResource, 0, len(rows))
	for i := range rows {
		data = append(data, vocationResource(&rows[i]))
	}

	meta := map[string]any{
		"page_number": pageNumber,
		"page_size":   pageSize,
		"total":       total,
	}

	return response.WriteWithMeta(c, fiber.StatusOK, data, meta)
}

// ListVocationDatatable godoc
// @Summary List vocation (datatable)
// @Description Datatable response with simple pagination params.
// @Tags OPC - Vocation
// @Produce json
// @Param page query int false "Page number (default 1)"
// @Param size query int false "Page size (default 20, max 100)"
// @Param limit query int false "Page size override (same as size)"
// @Param draw query int false "Draw counter (optional)"
// @Param search query string false "Search term"
// @Success 200 {object} dto.VocationDataTableResponse
// @Router /api/v1/vocation/get-all/dt [get]
func (h *VocationHandler) ListDatatable(c *fiber.Ctx) error {
	pageNumber := parseIntDefault(c.Query("page"), 1)
	if pageNumber < 1 {
		pageNumber = 1
	}
	length := parseIntDefault(c.Query("limit"), 0)
	if length <= 0 {
		length = parseIntDefault(c.Query("size"), 20)
	}
	if length > 100 {
		length = 100
	}
	if length < 1 {
		length = 20
	}
	start := (pageNumber - 1) * length
	draw := parseIntDefault(c.Query("draw"), pageNumber)
	search := c.Query("search")

	rows, total, err := h.svc.List(c.UserContext(), search, "", length, start)
	if err != nil {
		return writeVocationErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "List failed",
			Detail: safeInternalDetail(),
		}})
	}

	data := make([]dto.VocationResource, 0, len(rows))
	for i := range rows {
		data = append(data, vocationResource(&rows[i]))
	}

	meta := map[string]any{
		"draw":             draw,
		"records_total":    total,
		"records_filtered": total,
	}

	return response.WriteWithMeta(c, fiber.StatusOK, data, meta)
}

func vocationResource(v *vocation.Vocation) dto.VocationResource {
	return dto.VocationResource{
		Type: "vocation",
		ID:   idString(v.ID),
		Attributes: dto.VocationAttributes{
			Name:      v.Name,
			SortKey:   cloneIntPointer(v.SortKey),
			Note:      v.Note,
			IsActive:  v.IsActive,
			CreatedAt: v.CreatedAt.UTC().Format(time.RFC3339),
			CreatedBy: uuidStringOrEmpty(v.CreatedBy),
			UpdatedAt: v.UpdatedAt.UTC().Format(time.RFC3339),
			UpdatedBy: uuidStringOrEmpty(v.UpdatedBy),
			DeletedAt: timeStringOrEmpty(v.DeletedAt),
			DeletedBy: uuidStringOrEmpty(v.DeletedBy),
		},
	}
}

func writeVocationErrors(c *fiber.Ctx, status int, errs []jsonapi.ErrorObject) error {
	enriched := make([]jsonapi.ErrorObject, 0, len(errs))
	statusStr := strconv.Itoa(status)
	for i := range errs {
		e := errs[i]
		e.Status = statusStr
		def := inferVocationDef(status, e.Title, e.Detail)
		if strings.TrimSpace(e.Code) == "" {
			e.Code = def.Code
		}
		if strings.TrimSpace(e.ErrorCode) == "" {
			e.ErrorCode = def.ErrorCode
		}
		e.Detail = def.Message
		enriched = append(enriched, e)
	}
	return response.WriteErrors(c, status, enriched)
}

func inferVocationErrorCode(status int, title, detail string) (string, string) {
	def := inferVocationDef(status, title, detail)
	return def.Code, def.ErrorCode
}

func inferVocationDef(status int, title, detail string) apperrorsx.Def {
	lowerTitle := strings.ToLower(strings.TrimSpace(title))
	lowerDetail := strings.ToLower(strings.TrimSpace(detail))
	switch status {
	case fiber.StatusNotFound:
		return apperrorsx.ErrVocationNotFound
	case fiber.StatusConflict:
		return apperrorsx.ErrVocationRelationDelete
	case fiber.StatusUnprocessableEntity:
		switch {
		case strings.Contains(lowerDetail, "uuid is invalid"):
			return apperrorsx.ErrVocationInvalidUUID
		case strings.Contains(lowerDetail, "id is required"):
			return apperrorsx.ErrVocationIDRequired
		case strings.Contains(lowerDetail, "id does not match"):
			return apperrorsx.ErrVocationIDMismatch
		case strings.Contains(lowerDetail, "at least one attribute"):
			return apperrorsx.ErrVocationAttributesRequired
		case strings.Contains(lowerDetail, "name is required"), strings.Contains(lowerDetail, "name cannot be empty"):
			return apperrorsx.ErrVocationNameRequired
		default:
			return apperrorsx.ErrVocationInvalidPayload
		}
	case fiber.StatusBadRequest:
		switch {
		case strings.Contains(lowerTitle, "invalid json"):
			return apperrorsx.ErrVocationInvalidJSON
		case strings.Contains(lowerTitle, "create failed"):
			return apperrorsx.ErrVocationCreateFailed
		case strings.Contains(lowerTitle, "update failed"):
			return apperrorsx.ErrVocationUpdateFailed
		case strings.Contains(lowerTitle, "delete failed"):
			return apperrorsx.ErrVocationDeleteFailed
		case strings.Contains(lowerTitle, "list failed"):
			return apperrorsx.ErrVocationListFailed
		default:
			return apperrorsx.ErrVocationInvalidPayload
		}
	default:
		return apperrorsx.ErrInternal
	}
}
