package handlers

import (
	"strconv"
	"strings"
	"time"

	"github.com/gofiber/fiber/v2"

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

func NewICAOHandler(svc icao.Service) *ICAOHandler {
	return &ICAOHandler{
		svc:      svc,
		validate: validators.New(),
	}
}

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

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

	row := &icao.ICAO{
		ICAOCode:       code,
		Name:           strings.TrimSpace(stringOrDefault(req.Data.Attributes.Name, "")),
		SortKey:        cloneIntPointer(req.Data.Attributes.SortKey),
		Address:        strings.TrimSpace(stringOrDefault(req.Data.Attributes.Address, "")),
		LandlineNumber: strings.TrimSpace(stringOrDefault(req.Data.Attributes.LandlineNumber, "")),
		MobileNumber:   strings.TrimSpace(stringOrDefault(req.Data.Attributes.MobileNumber, "")),
		Email:          strings.TrimSpace(stringOrDefault(req.Data.Attributes.Email, "")),
		Note:           strings.TrimSpace(stringOrDefault(req.Data.Attributes.Note, "")),
		IsActive:       boolOrDefault(req.Data.Attributes.IsActive, true),
		CreatedBy:      actorUserID(c),
		UpdatedBy:      actorUserID(c),
	}
	if req.Data.Attributes.LandID != nil {
		landID, parseErr := parseNullableUUID(*req.Data.Attributes.LandID)
		if parseErr != nil {
			return writeICAOErrors(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.LandID = landID
	}
	if req.Data.Attributes.FederalStateID != nil {
		federalStateID, parseErr := parseNullableUUID(*req.Data.Attributes.FederalStateID)
		if parseErr != nil {
			return writeICAOErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
				Status: "422",
				Title:  "Validation error",
				Detail: "federal_state_id is invalid UUID",
				Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/federal_state_id"},
			}})
		}
		row.FederalStateID = federalStateID
	}

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

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

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

	if strings.TrimSpace(req.Data.ID) == "" {
		return writeICAOErrors(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 writeICAOErrors(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.ICAOCode == nil && attrs.LandID == nil && attrs.FederalStateID == nil && !attrs.SortKey.Set && attrs.Address == nil && attrs.LandlineNumber == nil && attrs.MobileNumber == nil && attrs.Email == nil && attrs.Note == nil && attrs.IsActive == nil {
		return writeICAOErrors(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 writeICAOErrors(c, fiber.StatusNotFound, []jsonapi.ErrorObject{{
			Status: "404",
			Title:  "Not found",
			Detail: "icao not found",
		}})
	}

	if attrs.ICAOCode != nil {
		v := strings.TrimSpace(*attrs.ICAOCode)
		if v == "" {
			return writeICAOErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
				Status: "422",
				Title:  "Validation error",
				Detail: "icao_code cannot be empty",
				Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/icao_code"},
			}})
		}
		existing.ICAOCode = v
	}
	if attrs.Name != nil {
		existing.Name = strings.TrimSpace(*attrs.Name)
	}
	if attrs.FederalStateID != nil {
		federalStateID, parseErr := parseNullableUUID(*attrs.FederalStateID)
		if parseErr != nil {
			return writeICAOErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
				Status: "422",
				Title:  "Validation error",
				Detail: "federal_state_id is invalid UUID",
				Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/federal_state_id"},
			}})
		}
		existing.FederalStateID = federalStateID
	}
	if attrs.LandID != nil {
		landID, parseErr := parseNullableUUID(*attrs.LandID)
		if parseErr != nil {
			return writeICAOErrors(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 = landID
	}
	if attrs.SortKey.Set {
		if attrs.SortKey.Valid {
			sortKey := attrs.SortKey.Value
			existing.SortKey = &sortKey
		} else {
			existing.SortKey = nil
		}
	}
	if attrs.Address != nil {
		existing.Address = strings.TrimSpace(*attrs.Address)
	}
	if attrs.LandlineNumber != nil {
		existing.LandlineNumber = strings.TrimSpace(*attrs.LandlineNumber)
	}
	if attrs.MobileNumber != nil {
		existing.MobileNumber = strings.TrimSpace(*attrs.MobileNumber)
	}
	if attrs.Email != nil {
		existing.Email = strings.TrimSpace(*attrs.Email)
	}
	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 writeICAOErrors(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, icaoResource(updated))
	}
	return response.Write(c, fiber.StatusOK, icaoResource(existing))
}

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

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

// ListICAO godoc
// @Summary List ICAO
// @Description JSON:API list with pagination, filtering and sorting. Sort values: icao_code, -icao_code, sortkey, -sortkey, address, -address, landline_number, -landline_number, mobile_number, -mobile_number, email, -email, note, -note, is_active, -is_active, created_at, -created_at, updated_at, -updated_at.
// @Tags Hospital - ICAO
// @Produce json
// @Param filter[search] query string false "Search by icao_code/address/contact"
// @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.ICAOListResponse
// @Router /api/v1/icao/get-all [get]
func (h *ICAOHandler) 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 writeICAOErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "List failed",
			Detail: safeInternalDetail(),
		}})
	}

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

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

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

// ListICAODatatable godoc
// @Summary List ICAO (datatable)
// @Description Datatable response with simple pagination params.
// @Tags Hospital - ICAO
// @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.ICAODataTableResponse
// @Router /api/v1/icao/get-all/dt [get]
func (h *ICAOHandler) 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 writeICAOErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "List failed",
			Detail: safeInternalDetail(),
		}})
	}

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

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

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

func icaoResource(row *icao.ICAO) dto.ICAOResource {
	return dto.ICAOResource{
		Type: "icao",
		ID:   idString(row.ID),
		Attributes: dto.ICAOAttributes{
			LandID:         idString(row.LandID),
			FederalStateID: idString(row.FederalStateID),
			FederalState:   federalStateNameOrEmpty(row),
			LandName:       landNameOrEmpty(row),
			LandISOCode:    landISOCodeOrEmpty(row),
			ICAOCode:       row.ICAOCode,
			Name:           row.Name,
			SortKey:        cloneIntPointer(row.SortKey),
			Address:        row.Address,
			LandlineNumber: row.LandlineNumber,
			MobileNumber:   row.MobileNumber,
			Email:          row.Email,
			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 parseNullableUUID(raw string) ([]byte, error) {
	value := strings.TrimSpace(raw)
	if value == "" {
		return nil, nil
	}
	return uuidv7.ParseString(value)
}

func federalStateNameOrEmpty(row *icao.ICAO) string {
	if row == nil || row.FederalState == nil {
		return ""
	}
	return row.FederalState.Name
}

func landNameOrEmpty(row *icao.ICAO) string {
	if row == nil {
		return ""
	}
	if row.Land != nil {
		return row.Land.Name
	}
	if row.FederalState == nil || row.FederalState.Land == nil {
		return ""
	}
	return row.FederalState.Land.Name
}

func landISOCodeOrEmpty(row *icao.ICAO) string {
	if row == nil {
		return ""
	}
	if row.Land != nil {
		return row.Land.LandISOCode
	}
	if row.FederalState == nil || row.FederalState.Land == nil {
		return ""
	}
	return row.FederalState.Land.LandISOCode
}

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

func inferICAODef(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.ErrICAONotFound
	case fiber.StatusConflict:
		return apperrorsx.ErrICAORelationDelete
	case fiber.StatusUnprocessableEntity:
		switch {
		case strings.Contains(lowerDetail, "uuid is invalid uuid"), strings.Contains(lowerDetail, "invalid uuid"):
			return apperrorsx.ErrICAOInvalidUUID
		case strings.Contains(lowerDetail, "id is required"):
			return apperrorsx.ErrICAOIDRequired
		case strings.Contains(lowerDetail, "id does not match path uuid"):
			return apperrorsx.ErrICAOIDMismatch
		case strings.Contains(lowerDetail, "at least one attribute must be provided"):
			return apperrorsx.ErrICAOAttributesRequired
		case strings.Contains(lowerDetail, "icao_code is required"), strings.Contains(lowerDetail, "icao_code cannot be empty"):
			return apperrorsx.ErrICAOCodeRequired
		case strings.Contains(lowerDetail, "land_id is invalid uuid"):
			return apperrorsx.ErrICAOLandIDInvalid
		case strings.Contains(lowerDetail, "federal_state_id is invalid uuid"):
			return apperrorsx.ErrICAOFederalStateInvalid
		default:
			return apperrorsx.ErrICAOInvalidPayload
		}
	case fiber.StatusBadRequest:
		switch {
		case strings.Contains(lowerTitle, "invalid json"):
			return apperrorsx.ErrICAOInvalidJSON
		case strings.Contains(lowerTitle, "create failed"):
			return apperrorsx.ErrICAOCreateFailed
		case strings.Contains(lowerTitle, "update failed"):
			return apperrorsx.ErrICAOUpdateFailed
		case strings.Contains(lowerTitle, "delete failed"):
			return apperrorsx.ErrICAODeleteFailed
		case strings.Contains(lowerTitle, "list failed"):
			return apperrorsx.ErrICAOListFailed
		default:
			return apperrorsx.ErrICAOInvalidPayload
		}
	default:
		return apperrorsx.ErrInternal
	}
}
