package handlers

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

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

	"wucher/internal/domain/forces_present"
	"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 ForcesPresentHandler struct {
	svc      forces_present.Service
	validate *validators.Validator
}

func NewForcesPresentHandler(svc forces_present.Service) *ForcesPresentHandler {
	return &ForcesPresentHandler{
		svc:      svc,
		validate: validators.New(),
	}
}

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

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

	row := &forces_present.ForcesPresent{
		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 writeForcesPresentErrors(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, forcesPresentResource(created))
	}
	return response.Write(c, fiber.StatusCreated, forcesPresentResource(row))
}

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

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

	if strings.TrimSpace(req.Data.ID) == "" {
		return writeForcesPresentErrors(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 writeForcesPresentErrors(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 writeForcesPresentErrors(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 writeForcesPresentErrors(c, fiber.StatusNotFound, []jsonapi.ErrorObject{{
			Status: "404",
			Title:  "Not found",
			Detail: "forces present not found",
		}})
	}

	if attrs.Name != nil {
		v := strings.TrimSpace(*attrs.Name)
		if v == "" {
			return writeForcesPresentErrors(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 writeForcesPresentErrors(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, forcesPresentResource(updated))
	}
	return response.Write(c, fiber.StatusOK, forcesPresentResource(existing))
}

// DeleteForcesPresent godoc
// @Summary Delete forces present
// @Tags OPC - Forces Present
// @Produce json
// @Param uuid path string true "Forces Present UUID (UUIDv7)"
// @Success 200 {object} dto.GenericDeleteResponse
// @Failure 404 {object} dto.ErrorResponse
// @Router /api/v1/forces-present/delete/{uuid} [delete]
func (h *ForcesPresentHandler) Delete(c *fiber.Ctx) error {
	uuidStr := c.Params("uuid")
	id, err := uuidv7.ParseString(uuidStr)
	if err != nil {
		return writeForcesPresentErrors(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 writeForcesPresentErrors(c, fiber.StatusNotFound, []jsonapi.ErrorObject{{
				Status: "404",
				Title:  "Not found",
				Detail: "forces present not found",
			}})
		}
		return writeForcesPresentErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "Delete failed",
			Detail: safeInternalDetail(),
		}})
	}

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

// ListForcesPresent godoc
// @Summary List forces present
// @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 - Forces Present
// @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.ForcesPresentListResponse
// @Router /api/v1/forces-present/get-all [get]
func (h *ForcesPresentHandler) 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 writeForcesPresentErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "List failed",
			Detail: safeInternalDetail(),
		}})
	}

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

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

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

// ListForcesPresentDatatable godoc
// @Summary List forces present (datatable)
// @Description Datatable response with simple pagination params.
// @Tags OPC - Forces Present
// @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.ForcesPresentDataTableResponse
// @Router /api/v1/forces-present/get-all/dt [get]
func (h *ForcesPresentHandler) 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 writeForcesPresentErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "List failed",
			Detail: safeInternalDetail(),
		}})
	}

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

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

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

func forcesPresentResource(row *forces_present.ForcesPresent) dto.ForcesPresentResource {
	return dto.ForcesPresentResource{
		Type: "forces_present",
		ID:   idString(row.ID),
		Attributes: dto.ForcesPresentAttributes{
			Name:      row.Name,
			SortKey:   cloneIntPointer(row.SortKey),
			Note:      row.Note,
			IsActive:  row.IsActive,
			CreatedAt: row.CreatedAt.UTC().Format(time.RFC3339),
			CreatedBy: uuidStringOrEmpty(row.CreatedBy),
			UpdatedAt: row.UpdatedAt.UTC().Format(time.RFC3339),
			UpdatedBy: uuidStringOrEmpty(row.UpdatedBy),
			DeletedAt: timeStringOrEmpty(row.DeletedAt),
			DeletedBy: uuidStringOrEmpty(row.DeletedBy),
		},
	}
}

func writeForcesPresentErrors(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
		if strings.TrimSpace(e.Code) == "" || strings.TrimSpace(e.ErrorCode) == "" {
			code, errorCode := inferForcesPresentErrorCode(status, e.Title, e.Detail)
			if strings.TrimSpace(e.Code) == "" {
				e.Code = code
			}
			if strings.TrimSpace(e.ErrorCode) == "" {
				e.ErrorCode = errorCode
			}
		}
		enriched = append(enriched, e)
	}
	return response.WriteErrors(c, status, enriched)
}

func inferForcesPresentErrorCode(status int, title, detail string) (string, string) {
	lowerTitle := strings.ToLower(strings.TrimSpace(title))
	lowerDetail := strings.ToLower(strings.TrimSpace(detail))
	switch status {
	case fiber.StatusNotFound:
		return apperrorsx.CodeForcesPresentNotFound, apperrorsx.ErrForcesPresentNotFound.ErrorCode
	case fiber.StatusConflict:
		return apperrorsx.CodeForcesPresentRelationDelete, apperrorsx.ErrForcesPresentRelationDelete.ErrorCode
	case fiber.StatusUnprocessableEntity:
		switch {
		case strings.Contains(lowerDetail, "uuid is invalid"):
			return apperrorsx.CodeForcesPresentInvalidUUID, apperrorsx.ErrForcesPresentInvalidUUID.ErrorCode
		case strings.Contains(lowerDetail, "id is required"):
			return apperrorsx.CodeForcesPresentIDRequired, apperrorsx.ErrForcesPresentIDRequired.ErrorCode
		case strings.Contains(lowerDetail, "id does not match"):
			return apperrorsx.CodeForcesPresentIDMismatch, apperrorsx.ErrForcesPresentIDMismatch.ErrorCode
		case strings.Contains(lowerDetail, "at least one attribute"):
			return apperrorsx.CodeForcesPresentAttributesRequired, apperrorsx.ErrForcesPresentAttributesRequired.ErrorCode
		case strings.Contains(lowerDetail, "name is required"), strings.Contains(lowerDetail, "name cannot be empty"):
			return apperrorsx.CodeForcesPresentNameRequired, apperrorsx.ErrForcesPresentNameRequired.ErrorCode
		default:
			return apperrorsx.CodeForcesPresentInvalidPayload, apperrorsx.ErrForcesPresentInvalidPayload.ErrorCode
		}
	case fiber.StatusBadRequest:
		switch {
		case strings.Contains(lowerTitle, "invalid json"):
			return apperrorsx.CodeForcesPresentInvalidJSON, apperrorsx.ErrForcesPresentInvalidJSON.ErrorCode
		case strings.Contains(lowerTitle, "create failed"):
			return apperrorsx.CodeForcesPresentCreateFailed, apperrorsx.ErrForcesPresentCreateFailed.ErrorCode
		case strings.Contains(lowerTitle, "update failed"):
			return apperrorsx.CodeForcesPresentUpdateFailed, apperrorsx.ErrForcesPresentUpdateFailed.ErrorCode
		case strings.Contains(lowerTitle, "delete failed"):
			if strings.Contains(lowerDetail, "relation") || strings.Contains(lowerDetail, "foreign key") || strings.Contains(lowerDetail, "constraint") {
				return apperrorsx.CodeForcesPresentRelationDelete, apperrorsx.ErrForcesPresentRelationDelete.ErrorCode
			}
			return apperrorsx.CodeForcesPresentDeleteFailed, apperrorsx.ErrForcesPresentDeleteFailed.ErrorCode
		case strings.Contains(lowerTitle, "list failed"):
			return apperrorsx.CodeForcesPresentListFailed, apperrorsx.ErrForcesPresentListFailed.ErrorCode
		default:
			return apperrorsx.CodeForcesPresentInvalidPayload, apperrorsx.ErrForcesPresentInvalidPayload.ErrorCode
		}
	default:
		return apperrorsx.CodeInternalServerError, apperrorsx.ErrInternal.ErrorCode
	}
}
