package handlers

import (
	"strings"
	"time"

	"github.com/gofiber/fiber/v2"

	"wucher/internal/domain/operation"
	"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 HEMSOperationCategoryHandler struct {
	svc      operation.HEMSOperationCategoryService
	validate *validators.Validator
}

func NewHEMSOperationCategoryHandler(svc operation.HEMSOperationCategoryService) *HEMSOperationCategoryHandler {
	return &HEMSOperationCategoryHandler{
		svc:      svc,
		validate: validators.New(),
	}
}

// CreateHEMSOperationCategory godoc
// @Summary Create HEMS operation category
// @Description Create a HEMS operation category.
// @Tags Operation - Category
// @Accept json
// @Produce json
// @Param request body dto.HEMSOperationCategoryCreateRequest true "JSON:API HEMS operation category create request"
// @Success 201 {object} dto.HEMSOperationCategoryResponse
// @Failure 422 {object} dto.ErrorResponse
// @Failure 400 {object} dto.ErrorResponse
// @Router /api/v1/hems-operation-category/create [post]
func (h *HEMSOperationCategoryHandler) Create(c *fiber.Ctx) error {
	var req dto.HEMSOperationCategoryCreateRequest
	if err := c.BodyParser(&req); err != nil {
		return response.WriteErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "Invalid JSON",
			Detail: safeInternalDetail(),
		}})
	}
	if errs := h.validate.ValidateStruct(req); errs != nil {
		return response.WriteErrors(c, fiber.StatusUnprocessableEntity, errs)
	}

	name := strings.TrimSpace(req.Data.Attributes.Name)
	if name == "" {
		return response.WriteErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "name is required",
			Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/name"},
		}})
	}
	typeValue := strings.ToLower(strings.TrimSpace(req.Data.Attributes.Type))
	if !operation.IsValidHEMSOperationCategoryType(typeValue) {
		return response.WriteErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "type must be one of: first, secondary, misuse",
			Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/type"},
		}})
	}

	row := &operation.HEMSOperationCategory{
		Name:      name,
		Type:      typeValue,
		CreatedBy: actorUserID(c),
		UpdatedBy: actorUserID(c),
	}
	if err := h.svc.Create(c.UserContext(), row); err != nil {
		return response.WriteErrors(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, hemsOperationCategoryResource(created))
	}
	return response.Write(c, fiber.StatusCreated, hemsOperationCategoryResource(row))
}

// GetHEMSOperationCategory godoc
// @Summary Get HEMS operation category by ID
// @Tags Operation - Category
// @Produce json
// @Param uuid path string true "HEMS operation category UUID (UUIDv7)"
// @Success 200 {object} dto.HEMSOperationCategoryResponse
// @Failure 422 {object} dto.ErrorResponse
// @Failure 404 {object} dto.ErrorResponse
// @Router /api/v1/hems-operation-category/get/{uuid} [get]
func (h *HEMSOperationCategoryHandler) Get(c *fiber.Ctx) error {
	id, err := uuidv7.ParseString(c.Params("uuid"))
	if err != nil {
		return response.WriteErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "uuid is invalid UUID",
			Source: &jsonapi.ErrorSource{Pointer: "/path/uuid"},
		}})
	}

	row, err := h.svc.GetByID(c.UserContext(), id)
	if err != nil || row == nil {
		return response.WriteErrors(c, fiber.StatusNotFound, []jsonapi.ErrorObject{{
			Status: "404",
			Title:  "Not found",
			Detail: "hems operation category not found",
		}})
	}

	return response.Write(c, fiber.StatusOK, hemsOperationCategoryResource(row))
}

// UpdateHEMSOperationCategory godoc
// @Summary Update HEMS operation category (partial)
// @Tags Operation - Category
// @Accept json
// @Produce json
// @Param uuid path string true "HEMS operation category UUID (UUIDv7)"
// @Param request body dto.HEMSOperationCategoryUpdateRequest true "JSON:API HEMS operation category update request"
// @Success 200 {object} dto.HEMSOperationCategoryResponse
// @Failure 422 {object} dto.ErrorResponse
// @Failure 404 {object} dto.ErrorResponse
// @Router /api/v1/hems-operation-category/update/{uuid} [patch]
func (h *HEMSOperationCategoryHandler) Update(c *fiber.Ctx) error {
	id, err := uuidv7.ParseString(c.Params("uuid"))
	if err != nil {
		return response.WriteErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "uuid is invalid UUID",
			Source: &jsonapi.ErrorSource{Pointer: "/path/uuid"},
		}})
	}

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

	attrs := req.Data.Attributes
	if attrs.Name == nil && attrs.Type == nil {
		return response.WriteErrors(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 response.WriteErrors(c, fiber.StatusNotFound, []jsonapi.ErrorObject{{
			Status: "404",
			Title:  "Not found",
			Detail: "hems operation category not found",
		}})
	}
	if attrs.Name != nil {
		v := strings.TrimSpace(*attrs.Name)
		if v == "" {
			return response.WriteErrors(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.Type != nil {
		v := strings.ToLower(strings.TrimSpace(*attrs.Type))
		if !operation.IsValidHEMSOperationCategoryType(v) {
			return response.WriteErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
				Status: "422",
				Title:  "Validation error",
				Detail: "type must be one of: first, secondary, misuse",
				Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/type"},
			}})
		}
		existing.Type = v
	}
	existing.UpdatedBy = actorUserID(c)

	if err := h.svc.Update(c.UserContext(), existing); err != nil {
		return response.WriteErrors(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, hemsOperationCategoryResource(updated))
	}
	return response.Write(c, fiber.StatusOK, hemsOperationCategoryResource(existing))
}

// DeleteHEMSOperationCategory godoc
// @Summary Delete HEMS operation category
// @Tags Operation - Category
// @Produce json
// @Param uuid path string true "HEMS operation category UUID (UUIDv7)"
// @Success 200 {object} dto.GenericDeleteResponse
// @Failure 422 {object} dto.ErrorResponse
// @Failure 400 {object} dto.ErrorResponse
// @Failure 404 {object} dto.ErrorResponse
// @Router /api/v1/hems-operation-category/delete/{uuid} [delete]
func (h *HEMSOperationCategoryHandler) Delete(c *fiber.Ctx) error {
	id, err := uuidv7.ParseString(c.Params("uuid"))
	if err != nil {
		return response.WriteErrors(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 {
		return writeDeleteError(c, err)
	}

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

// ListHEMSOperationCategory godoc
// @Summary List HEMS operation categories
// @Tags Operation - Category
// @Produce json
// @Param filter[search] query string false "Search by name/type"
// @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.HEMSOperationCategoryListResponse
// @Router /api/v1/hems-operation-category/get-all [get]
func (h *HEMSOperationCategoryHandler) List(c *fiber.Ctx) error {
	filter := c.Query("filter[search]")
	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 response.WriteErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "List failed",
			Detail: safeInternalDetail(),
		}})
	}

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

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

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

// ListHEMSOperationCategoryDatatable godoc
// @Summary List HEMS operation categories (datatable)
// @Tags Operation - Category
// @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.HEMSOperationCategoryDataTableResponse
// @Router /api/v1/hems-operation-category/get-all/dt [get]
func (h *HEMSOperationCategoryHandler) 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 response.WriteErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "List failed",
			Detail: safeInternalDetail(),
		}})
	}

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

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

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

func hemsOperationCategoryResource(row *operation.HEMSOperationCategory) dto.HEMSOperationCategoryResource {
	return dto.HEMSOperationCategoryResource{
		Type: "hems_operation_category",
		ID:   idString(row.ID),
		Attributes: dto.HEMSOperationCategoryAttributes{
			Name:      row.Name,
			Type:      row.Type,
			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),
		},
	}
}
