package handlers

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

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

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

func NewFederalStateHandler(svc federal_state.Service) *FederalStateHandler {
	return &FederalStateHandler{
		svc:      svc,
		validate: validators.New(),
	}
}

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

	name := strings.TrimSpace(req.Data.Attributes.Name)
	if name == "" {
		return writeFederalStateErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "name is required",
			Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/name"},
		}})
	}
	landID, err := uuidv7.ParseString(strings.TrimSpace(req.Data.Attributes.LandID))
	if err != nil {
		return writeFederalStateErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "land_id is invalid UUID",
			Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/land_id"},
		}})
	}

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

	if err := h.svc.Create(c.UserContext(), row); err != nil {
		return writeFederalStateErrors(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, federalStateResource(created))
	}
	return response.Write(c, fiber.StatusCreated, federalStateResource(row))
}

// UpdateFederalState godoc
// @Summary Update federal state (partial)
// @Description Patch federal state by ID.
// @Tags Hospital - Federal State
// @Accept json
// @Produce json
// @Param id path string true "Federal State ID (UUIDv7)"
// @Param request body dto.FederalStateUpdateRequest true "JSON:API federal state update request"
// @Success 200 {object} dto.FederalStateResponse
// @Failure 422 {object} dto.ErrorResponse
// @Failure 404 {object} dto.ErrorResponse
// @Router /api/v1/federal-state/update/{id} [patch]
func (h *FederalStateHandler) Update(c *fiber.Ctx) error {
	idStr := c.Params("id")
	id, err := uuidv7.ParseString(idStr)
	if err != nil {
		return writeFederalStateErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "id is invalid UUID",
			Source: &jsonapi.ErrorSource{Pointer: "/path/id"},
		}})
	}

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

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

	attrs := req.Data.Attributes
	if attrs.Name == nil && attrs.Note == nil && attrs.LandID == nil && !attrs.SortKey.Set && attrs.IsActive == nil {
		return writeFederalStateErrors(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 writeFederalStateErrors(c, fiber.StatusNotFound, []jsonapi.ErrorObject{{
			Status: "404",
			Title:  "Not found",
			Detail: "federal state not found",
		}})
	}

	if attrs.Name != nil {
		v := strings.TrimSpace(*attrs.Name)
		if v == "" {
			return writeFederalStateErrors(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.Note != nil {
		existing.Note = strings.TrimSpace(*attrs.Note)
	}
	if attrs.LandID != nil {
		parsed, parseErr := uuidv7.ParseString(strings.TrimSpace(*attrs.LandID))
		if parseErr != nil {
			return writeFederalStateErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
				Status: "422",
				Title:  "Validation error",
				Detail: "land_id is invalid UUID",
				Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/land_id"},
			}})
		}
		existing.LandID = parsed
		// Prevent stale preloaded belongs-to association from overriding new foreign key on Save.
		if existing.Land != nil && !bytes.Equal(existing.Land.ID, parsed) {
			existing.Land = nil
		}
	}
	if attrs.SortKey.Set {
		if attrs.SortKey.Valid {
			sortKey := attrs.SortKey.Value
			existing.SortKey = &sortKey
		} else {
			existing.SortKey = nil
		}
	}
	if attrs.IsActive != nil {
		existing.IsActive = *attrs.IsActive
	}
	existing.UpdatedBy = actorUserID(c)

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

// DeleteFederalState godoc
// @Summary Delete federal state
// @Tags Hospital - Federal State
// @Produce json
// @Param id path string true "Federal State ID (UUIDv7)"
// @Success 200 {object} dto.FederalStateDeleteResponse
// @Failure 404 {object} dto.ErrorResponse
// @Router /api/v1/federal-state/delete/{id} [delete]
func (h *FederalStateHandler) Delete(c *fiber.Ctx) error {
	idStr := c.Params("id")
	id, err := uuidv7.ParseString(idStr)
	if err != nil {
		return writeFederalStateErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "id is invalid UUID",
			Source: &jsonapi.ErrorSource{Pointer: "/path/id"},
		}})
	}

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

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

// ListFederalState godoc
// @Summary List federal state
// @Description JSON:API list with pagination, filtering and sorting. Sort values: name, -name, sortkey, -sortkey, is_active, -is_active, created_at, -created_at, updated_at, -updated_at.
// @Tags Hospital - Federal State
// @Produce json
// @Param filter[search] query string false "Search by name"
// @Param land_id query string false "Filter federal state by land UUID"
// @Param land_name query string false "Filter federal state by land name"
// @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.FederalStateListResponse
// @Router /api/v1/federal-state/get-all [get]
func (h *FederalStateHandler) List(c *fiber.Ctx) error {
	filter := c.Query("filter[search]")
	if filter == "" {
		filter = c.Query("filter[name]")
	}
	landName := c.Query("land_name")
	if landName == "" {
		landName = c.Query("filter[land_name]")
	}

	landIDQuery := c.Query("land_id")
	landID, landIDErr := parseOptionalUUID(&landIDQuery, "/query/land_id")
	if landIDErr != nil {
		landIDErr.Detail = "land_id is invalid UUID"
		return writeFederalStateErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{*landIDErr})
	}

	pageNumber := parseIntDefault(c.Query("page[number]"), 1)
	pageSize := parseIntDefault(c.Query("page[size]"), 20)
	if pageSize > 100 {
		pageSize = 100
	}
	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, landID, landName)
	if err != nil {
		return writeFederalStateErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "List failed",
			Detail: safeInternalDetail(),
		}})
	}

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

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

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

// ListFederalStateDatatable godoc
// @Summary List federal state (datatable)
// @Description Datatable response with simple pagination params.
// @Tags Hospital - Federal State
// @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"
// @Param filter[search] query string false "Search by name"
// @Param land_id query string false "Filter federal state by land UUID"
// @Param land_name query string false "Filter federal state by land name"
// @Success 200 {object} dto.FederalStateDataTableResponse
// @Router /api/v1/federal-state/get-all/dt [get]
func (h *FederalStateHandler) 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")
	if search == "" {
		search = c.Query("filter[search]")
	}
	if search == "" {
		search = c.Query("filter[name]")
	}
	landName := c.Query("land_name")
	if landName == "" {
		landName = c.Query("filter[land_name]")
	}
	landIDQuery := c.Query("land_id")
	landID, landIDErr := parseOptionalUUID(&landIDQuery, "/query/land_id")
	if landIDErr != nil {
		landIDErr.Detail = "land_id is invalid UUID"
		return writeFederalStateErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{*landIDErr})
	}

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

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

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

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

func federalStateResource(row *federal_state.FederalState) dto.FederalStateResource {
	return dto.FederalStateResource{
		Type: "federal_state",
		ID:   idString(row.ID),
		Attributes: dto.FederalStateAttributes{
			Name:        row.Name,
			Note:        row.Note,
			LandID:      idString(row.LandID),
			LandName:    landNameFromFederalState(row),
			LandISOCode: landISOCodeFromFederalState(row),
			SortKey:     cloneIntPointer(row.SortKey),
			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 landNameFromFederalState(row *federal_state.FederalState) string {
	if row == nil || row.Land == nil {
		return ""
	}
	return row.Land.Name
}

func landISOCodeFromFederalState(row *federal_state.FederalState) string {
	if row == nil || row.Land == nil {
		return ""
	}
	return row.Land.LandISOCode
}

func writeFederalStateErrors(c *fiber.Ctx, status int, errs []jsonapi.ErrorObject) error {
	statusStr := strconv.Itoa(status)
	enriched := make([]jsonapi.ErrorObject, 0, len(errs))
	for i := range errs {
		e := errs[i]
		e.Status = statusStr
		def := inferFederalStateDef(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 inferFederalStateErrorCode(status int, title, detail string) (string, string) {
	def := inferFederalStateDef(status, title, detail)
	return def.Code, def.ErrorCode
}

func inferFederalStateDef(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.ErrFederalStateNotFound
	case fiber.StatusConflict:
		return apperrorsx.ErrFederalStateRelationDelete
	case fiber.StatusUnprocessableEntity:
		switch {
		case strings.Contains(lowerDetail, "land_id is invalid uuid"):
			return apperrorsx.ErrFederalStateLandIDInvalid
		case strings.Contains(lowerDetail, "id is invalid uuid"), strings.Contains(lowerDetail, "invalid uuid"):
			return apperrorsx.ErrFederalStateInvalidID
		case strings.Contains(lowerDetail, "id is required"):
			return apperrorsx.ErrFederalStateIDRequired
		case strings.Contains(lowerDetail, "id does not match path id"):
			return apperrorsx.ErrFederalStateIDMismatch
		case strings.Contains(lowerDetail, "at least one attribute must be provided"):
			return apperrorsx.ErrFederalStateAttributesRequired
		case strings.Contains(lowerDetail, "name is required"), strings.Contains(lowerDetail, "name cannot be empty"):
			return apperrorsx.ErrFederalStateNameRequired
		default:
			return apperrorsx.ErrFederalStateInvalidPayload
		}
	case fiber.StatusBadRequest:
		switch {
		case strings.Contains(lowerTitle, "invalid json"):
			return apperrorsx.ErrFederalStateInvalidJSON
		case strings.Contains(lowerTitle, "create failed"):
			return apperrorsx.ErrFederalStateCreateFailed
		case strings.Contains(lowerTitle, "update failed"):
			return apperrorsx.ErrFederalStateUpdateFailed
		case strings.Contains(lowerTitle, "delete failed"):
			return apperrorsx.ErrFederalStateDeleteFailed
		case strings.Contains(lowerTitle, "list failed"):
			return apperrorsx.ErrFederalStateListFailed
		default:
			return apperrorsx.ErrFederalStateInvalidPayload
		}
	default:
		return apperrorsx.ErrInternal
	}
}
