package handlers

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

	mysqldriver "github.com/go-sql-driver/mysql"
	"github.com/gofiber/fiber/v2"
	"gorm.io/gorm"

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

func NewLandHandler(svc land.Service) *LandHandler {
	return &LandHandler{
		svc:      svc,
		validate: validators.New(),
	}
}

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

	name := strings.TrimSpace(req.Data.Attributes.Name)
	if name == "" {
		return writeLandErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "name is required",
			Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/name"},
		}})
	}
	isoCode, isoOK := normalizeOptionalISOCode(req.Data.Attributes.ISOCode)
	if !isoOK {
		return writeLandErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "iso_code must be empty or 2 uppercase letters (A-Z)",
			Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/iso_code"},
		}})
	}

	row := &land.Land{
		Name:        name,
		Note:        strings.TrimSpace(stringOrDefault(req.Data.Attributes.Note, "")),
		LandISOCode: isoCode,
		BMDExportID: normalizeOptionalBMDExportID(req.Data.Attributes.BMDExportID),
		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 {
		if isLandISOCodeDuplicateError(err) {
			return writeLandErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
				Status: "422",
				Title:  "Validation error",
				Detail: "iso_code already exists",
				Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/iso_code"},
			}})
		}
		return writeLandErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "Create failed",
			Detail: safeInternalDetail(),
		}})
	}

	created, err := h.getByIDView(c.UserContext(), row.ID)
	if err == nil && created != nil {
		return response.Write(c, fiber.StatusCreated, landResource(created))
	}
	return response.Write(c, fiber.StatusCreated, landResource(&dto.LandView{Row: *row}))
}

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

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

	if strings.TrimSpace(req.Data.ID) == "" {
		return writeLandErrors(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 writeLandErrors(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.ISOCode == nil && attrs.BMDExportID == nil && !attrs.SortKey.Set && attrs.IsActive == nil {
		return writeLandErrors(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 writeLandErrors(c, fiber.StatusNotFound, []jsonapi.ErrorObject{{
			Status: "404",
			Title:  "Not found",
			Detail: "land not found",
		}})
	}

	if attrs.Name != nil {
		v := strings.TrimSpace(*attrs.Name)
		if v == "" {
			return writeLandErrors(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.ISOCode != nil {
		isoCode, isoOK := normalizeOptionalISOCode(*attrs.ISOCode)
		if !isoOK {
			return writeLandErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
				Status: "422",
				Title:  "Validation error",
				Detail: "iso_code must be empty or 2 uppercase letters (A-Z)",
				Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/iso_code"},
			}})
		}
		existing.LandISOCode = isoCode
	}
	if attrs.BMDExportID != nil {
		existing.BMDExportID = normalizeOptionalBMDExportID(attrs.BMDExportID)
	}
	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 {
		if isLandISOCodeDuplicateError(err) {
			return writeLandErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
				Status: "422",
				Title:  "Validation error",
				Detail: "iso_code already exists",
				Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/iso_code"},
			}})
		}
		return writeLandErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "Update failed",
			Detail: safeInternalDetail(),
		}})
	}

	updated, err := h.getByIDView(c.UserContext(), existing.ID)
	if err == nil && updated != nil {
		return response.Write(c, fiber.StatusOK, landResource(updated))
	}
	return response.Write(c, fiber.StatusOK, landResource(&dto.LandView{Row: *existing}))
}

// DeleteLand godoc
// @Summary Delete land
// @Tags Hospital - Land
// @Produce json
// @Param id path string true "Land ID (UUIDv7)"
// @Success 200 {object} dto.GenericDeleteResponse
// @Failure 404 {object} dto.ErrorResponse
// @Router /api/v1/land/delete/{id} [delete]
func (h *LandHandler) Delete(c *fiber.Ctx) error {
	idStr := c.Params("id")
	id, err := uuidv7.ParseString(idStr)
	if err != nil {
		return writeLandErrors(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 writeLandErrors(c, fiber.StatusNotFound, []jsonapi.ErrorObject{{
				Status: "404",
				Title:  "Not found",
				Detail: "land not found",
			}})
		}
		if conflict, ok := apperrors.AsDeleteConflict(err); ok {
			return writeLandErrors(c, fiber.StatusConflict, []jsonapi.ErrorObject{{
				Status: "409",
				Title:  "Conflict",
				Detail: conflict.Error(),
			}})
		}
		return writeLandErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "Delete failed",
			Detail: safeInternalDetail(),
		}})
	}

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

// ListLand godoc
// @Summary List land
// @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 - Land
// @Produce json
// @Param filter[search] query string false "Search by 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.LandListResponse
// @Router /api/v1/land/get-all [get]
func (h *LandHandler) 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
	sort := c.Query("sort")

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

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

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

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

// ListLandDatatable godoc
// @Summary List land (datatable)
// @Description Datatable response with simple pagination params.
// @Tags Hospital - Land
// @Produce json
// @Param page query int false "Page number (default 1)"
// @Param size query int false "Page size (default 20, max 1000)"
// @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.LandDataTableResponse
// @Router /api/v1/land/get-all/dt [get]
func (h *LandHandler) 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 > 1000 {
		length = 1000
	}
	if length < 1 {
		length = 20
	}
	start := (pageNumber - 1) * length
	draw := parseIntDefault(c.Query("draw"), pageNumber)
	search := c.Query("search")

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

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

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

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

func landResource(row *dto.LandView) dto.LandResource {
	return dto.LandResource{
		Type: "land",
		ID:   idString(row.Row.ID),
		Attributes: dto.LandAttributes{
			Name:              row.Row.Name,
			Note:              row.Row.Note,
			ISOCode:           row.Row.LandISOCode,
			BMDExportID:       cloneStringPointer(row.Row.BMDExportID),
			FederalStateTotal: row.FederalStateTotal,
			FederalStateList:  landFederalStateDTOs(row.FederalStateList),
			SortKey:           cloneIntPointer(row.Row.SortKey),
			IsActive:          row.Row.IsActive,
			CreatedAt:         row.Row.CreatedAt.UTC().Format(time.RFC3339),
			CreatedBy:         uuidStringOrEmpty(row.Row.CreatedBy),
			UpdatedAt:         row.Row.UpdatedAt.UTC().Format(time.RFC3339),
			UpdatedBy:         uuidStringOrEmpty(row.Row.UpdatedBy),
			DeletedAt:         timeStringOrEmpty(row.Row.DeletedAt),
			DeletedBy:         uuidStringOrEmpty(row.Row.DeletedBy),
		},
	}
}

func normalizeOptionalBMDExportID(raw *string) *string {
	if raw == nil {
		return nil
	}
	v := strings.TrimSpace(*raw)
	if v == "" {
		return nil
	}
	return &v
}

func cloneStringPointer(v *string) *string {
	if v == nil {
		return nil
	}
	out := *v
	return &out
}

func normalizeOptionalISOCode(raw string) (string, bool) {
	code := strings.ToUpper(strings.TrimSpace(raw))
	if code == "" {
		return "", true
	}
	if len(code) != 2 {
		return "", false
	}
	for _, ch := range code {
		if ch < 'A' || ch > 'Z' {
			return "", false
		}
	}
	return code, true
}

func landFederalStateDTOs(rows []dto.LandFederalStateView) []dto.LandFederalStateDTO {
	if len(rows) == 0 {
		return nil
	}
	out := make([]dto.LandFederalStateDTO, 0, len(rows))
	for i := range rows {
		out = append(out, dto.LandFederalStateDTO{
			ID:   idString(rows[i].ID),
			Name: rows[i].Name,
		})
	}
	return out
}

func (h *LandHandler) getByIDView(ctx context.Context, id []byte) (*dto.LandView, error) {
	if svc, ok := h.svc.(interface {
		GetByIDView(context.Context, []byte) (*dto.LandView, error)
	}); ok {
		return svc.GetByIDView(ctx, id)
	}
	row, err := h.svc.GetByID(ctx, id)
	if err != nil || row == nil {
		return nil, err
	}
	return &dto.LandView{Row: *row}, nil
}

func isLandISOCodeDuplicateError(err error) bool {
	if errors.Is(err, gorm.ErrDuplicatedKey) {
		return true
	}

	var mysqlErr *mysqldriver.MySQLError
	if !errors.As(err, &mysqlErr) || mysqlErr.Number != 1062 {
		return false
	}

	msg := strings.ToLower(mysqlErr.Message)
	return strings.Contains(msg, "uq_lands_land_iso_code") || strings.Contains(msg, "land_iso_code")
}

func (h *LandHandler) listView(ctx context.Context, filter, sort string, limit, offset int) ([]dto.LandView, int64, error) {
	if svc, ok := h.svc.(interface {
		ListView(context.Context, string, string, int, int) ([]dto.LandView, int64, error)
	}); ok {
		return svc.ListView(ctx, filter, sort, limit, offset)
	}
	rows, total, err := h.svc.List(ctx, filter, sort, limit, offset)
	if err != nil {
		return nil, 0, err
	}
	views := make([]dto.LandView, 0, len(rows))
	for i := range rows {
		views = append(views, dto.LandView{Row: rows[i]})
	}
	return views, total, nil
}

func writeLandErrors(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 := inferLandDef(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 inferLandErrorCode(status int, title, detail string) (string, string) {
	def := inferLandDef(status, title, detail)
	return def.Code, def.ErrorCode
}

func inferLandDef(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.ErrLandNotFound
	case fiber.StatusConflict:
		return apperrorsx.ErrLandRelationDelete
	case fiber.StatusUnprocessableEntity:
		switch {
		case strings.Contains(lowerDetail, "id is invalid uuid"), strings.Contains(lowerDetail, "invalid uuid"):
			return apperrorsx.ErrLandInvalidID
		case strings.Contains(lowerDetail, "id is required"):
			return apperrorsx.ErrLandIDRequired
		case strings.Contains(lowerDetail, "id does not match path id"):
			return apperrorsx.ErrLandIDMismatch
		case strings.Contains(lowerDetail, "at least one attribute must be provided"):
			return apperrorsx.ErrLandAttributesRequired
		case strings.Contains(lowerDetail, "name is required"), strings.Contains(lowerDetail, "name cannot be empty"):
			return apperrorsx.ErrLandNameRequired
		case strings.Contains(lowerDetail, "iso_code must"):
			return apperrorsx.ErrLandISOCodeInvalid
		case strings.Contains(lowerDetail, "iso_code already exists"):
			return apperrorsx.ErrLandISOCodeDuplicate
		default:
			return apperrorsx.ErrLandInvalidPayload
		}
	case fiber.StatusBadRequest:
		switch {
		case strings.Contains(lowerTitle, "invalid json"):
			return apperrorsx.ErrLandInvalidJSON
		case strings.Contains(lowerTitle, "create failed"):
			return apperrorsx.ErrLandCreateFailed
		case strings.Contains(lowerTitle, "update failed"):
			return apperrorsx.ErrLandUpdateFailed
		case strings.Contains(lowerTitle, "delete failed"):
			return apperrorsx.ErrLandDeleteFailed
		case strings.Contains(lowerTitle, "list failed"):
			return apperrorsx.ErrLandListFailed
		default:
			return apperrorsx.ErrLandInvalidPayload
		}
	default:
		return apperrorsx.ErrInternal
	}
}
