package handlers

import (
	"encoding/hex"
	"errors"
	"strconv"
	"strings"
	"time"

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

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

func NewHealthInsuranceCompaniesHandler(svc health_insurance_companies.Service) *HealthInsuranceCompaniesHandler {
	return &HealthInsuranceCompaniesHandler{
		svc:      svc,
		validate: validators.New(),
	}
}

// CreateHealthInsuranceCompany godoc
// @Summary Create health insurance company
// @Description Create a health insurance company row.
// @Tags Hospital - Health Insurance Companies
// @Accept json
// @Produce json
// @Param request body dto.HealthInsuranceCompanyCreateRequest true "JSON:API health insurance company create request"
// @Success 201 {object} dto.HealthInsuranceCompanyResponse
// @Failure 422 {object} dto.ErrorResponse
// @Failure 400 {object} dto.ErrorResponse
// @Router /api/v1/health-insurance-companies/create [post]
func (h *HealthInsuranceCompaniesHandler) Create(c *fiber.Ctx) error {
	var req dto.HealthInsuranceCompanyCreateRequest
	if err := c.BodyParser(&req); err != nil {
		return writeHealthInsuranceErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "Invalid JSON",
			Detail: safeInternalDetail(),
		}})
	}
	if errs := h.validate.ValidateStruct(req); errs != nil {
		return writeHealthInsuranceErrors(c, fiber.StatusUnprocessableEntity, errs)
	}

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

	row := &health_insurance_companies.HealthInsuranceCompany{
		Name:         name,
		SortKey:      cloneIntPointer(req.Data.Attributes.SortKey),
		State:        strings.TrimSpace(stringOrDefault(req.Data.Attributes.State, "")),
		Address:      strings.TrimSpace(stringOrDefault(req.Data.Attributes.Address, "")),
		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 writeHealthInsuranceErrors(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 err := h.svc.Create(c.UserContext(), row); err != nil {
		return writeHealthInsuranceErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "Create failed",
			Detail: safeInternalDetail(),
		}})
	}

	created, err := h.svc.GetByID(c.UserContext(), row.ID)
	stateDetails, _ := h.svc.ResolveStateDetails(c.UserContext(), []string{row.State})
	landDetails, _ := h.svc.ResolveLandDetails(c.UserContext(), collectHealthInsuranceLandIDs([]health_insurance_companies.HealthInsuranceCompany{*row}))
	if err == nil && created != nil {
		return response.Write(c, fiber.StatusCreated, healthInsuranceCompanyResource(created, stateDetails, landDetails))
	}
	return response.Write(c, fiber.StatusCreated, healthInsuranceCompanyResource(row, stateDetails, landDetails))
}

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

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

	if strings.TrimSpace(req.Data.ID) == "" {
		return writeHealthInsuranceErrors(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 writeHealthInsuranceErrors(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.LandID == nil && attrs.State == nil && attrs.Address == nil && attrs.MobileNumber == nil && attrs.Email == nil && attrs.Note == nil && attrs.IsActive == nil {
		return writeHealthInsuranceErrors(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 writeHealthInsuranceErrors(c, fiber.StatusNotFound, []jsonapi.ErrorObject{{
			Status: "404",
			Title:  "Not found",
			Detail: "health insurance company not found",
		}})
	}

	if attrs.Name != nil {
		v := strings.TrimSpace(*attrs.Name)
		if v == "" {
			return writeHealthInsuranceErrors(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.LandID != nil {
		landID, parseErr := parseNullableUUID(*attrs.LandID)
		if parseErr != nil {
			return writeHealthInsuranceErrors(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.State != nil {
		existing.State = strings.TrimSpace(*attrs.State)
	}
	if attrs.Address != nil {
		existing.Address = strings.TrimSpace(*attrs.Address)
	}
	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 writeHealthInsuranceErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "Update failed",
			Detail: safeInternalDetail(),
		}})
	}

	updated, err := h.svc.GetByID(c.UserContext(), existing.ID)
	stateDetails, _ := h.svc.ResolveStateDetails(c.UserContext(), []string{existing.State})
	landDetails, _ := h.svc.ResolveLandDetails(c.UserContext(), collectHealthInsuranceLandIDs([]health_insurance_companies.HealthInsuranceCompany{*existing}))
	if err == nil && updated != nil {
		return response.Write(c, fiber.StatusOK, healthInsuranceCompanyResource(updated, stateDetails, landDetails))
	}
	return response.Write(c, fiber.StatusOK, healthInsuranceCompanyResource(existing, stateDetails, landDetails))
}

// DeleteHealthInsuranceCompany godoc
// @Summary Delete health insurance company
// @Tags Hospital - Health Insurance Companies
// @Produce json
// @Param uuid path string true "Health Insurance Company UUID (UUIDv7)"
// @Success 200 {object} dto.GenericDeleteResponse
// @Failure 404 {object} dto.ErrorResponse
// @Router /api/v1/health-insurance-companies/delete/{uuid} [delete]
func (h *HealthInsuranceCompaniesHandler) Delete(c *fiber.Ctx) error {
	uuidStr := c.Params("uuid")
	id, err := uuidv7.ParseString(uuidStr)
	if err != nil {
		return writeHealthInsuranceErrors(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 writeHealthInsuranceErrors(c, fiber.StatusNotFound, []jsonapi.ErrorObject{{Status: "404", Title: "Not found", Detail: "health insurance company not found"}})
		}
		if _, ok := apperrors.AsDeleteConflict(err); ok {
			return writeHealthInsuranceErrors(c, fiber.StatusConflict, []jsonapi.ErrorObject{{Status: "409", Title: "Conflict", Detail: safeInternalDetail()}})
		}
		return writeHealthInsuranceErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{Status: "400", Title: "Delete failed", Detail: safeInternalDetail()}})
	}

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

// ListHealthInsuranceCompanies godoc
// @Summary List health insurance companies
// @Description JSON:API list with pagination, filtering and sorting. Sort values: name, -name, sortkey, -sortkey, state, -state, address, -address, mobile_number, -mobile_number, email, -email, note, -note, is_active, -is_active, created_at, -created_at, updated_at, -updated_at.
// @Tags Hospital - Health Insurance Companies
// @Produce json
// @Param filter[search] query string false "Search by name/state/address/mobile/email"
// @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.HealthInsuranceCompanyListResponse
// @Router /api/v1/health-insurance-companies/get-all [get]
func (h *HealthInsuranceCompaniesHandler) 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 writeHealthInsuranceErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "List failed",
			Detail: safeInternalDetail(),
		}})
	}

	stateDetails, _ := h.svc.ResolveStateDetails(c.UserContext(), collectHealthInsuranceStateNames(rows))
	landDetails, _ := h.svc.ResolveLandDetails(c.UserContext(), collectHealthInsuranceLandIDs(rows))
	data := make([]dto.HealthInsuranceCompanyResource, 0, len(rows))
	for i := range rows {
		data = append(data, healthInsuranceCompanyResource(&rows[i], stateDetails, landDetails))
	}

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

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

// ListHealthInsuranceCompaniesDatatable godoc
// @Summary List health insurance companies (datatable)
// @Description Datatable response with simple pagination params.
// @Tags Hospital - Health Insurance Companies
// @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.HealthInsuranceCompanyDataTableResponse
// @Router /api/v1/health-insurance-companies/get-all/dt [get]
func (h *HealthInsuranceCompaniesHandler) 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 writeHealthInsuranceErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "List failed",
			Detail: safeInternalDetail(),
		}})
	}

	stateDetails, _ := h.svc.ResolveStateDetails(c.UserContext(), collectHealthInsuranceStateNames(rows))
	landDetails, _ := h.svc.ResolveLandDetails(c.UserContext(), collectHealthInsuranceLandIDs(rows))
	data := make([]dto.HealthInsuranceCompanyResource, 0, len(rows))
	for i := range rows {
		data = append(data, healthInsuranceCompanyResource(&rows[i], stateDetails, landDetails))
	}

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

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

func healthInsuranceCompanyResource(row *health_insurance_companies.HealthInsuranceCompany, stateDetails map[string]health_insurance_companies.StateDetail, landDetails map[string]health_insurance_companies.LandDetail) dto.HealthInsuranceCompanyResource {
	stateDetail := resolveHealthInsuranceStateDetail(row.State, stateDetails)
	landDetail := resolveHealthInsuranceLandDetail(row.LandID, landDetails)
	if stateDetail.LandID == "" {
		stateDetail.LandID = landDetail.LandID
	}
	if stateDetail.LandName == "" {
		stateDetail.LandName = landDetail.LandName
	}
	if stateDetail.LandISOCode == "" {
		stateDetail.LandISOCode = landDetail.LandISOCode
	}
	return dto.HealthInsuranceCompanyResource{
		Type: "health_insurance_company",
		ID:   idString(row.ID),
		Attributes: dto.HealthInsuranceCompanyAttributes{
			LandID:         landIDString(row, stateDetail),
			FederalStateID: stateDetail.FederalStateID,
			FederalState:   stateDetail.FederalState,
			LandName:       stateDetail.LandName,
			LandISOCode:    stateDetail.LandISOCode,
			Name:           row.Name,
			SortKey:        cloneIntPointer(row.SortKey),
			State:          row.State,
			Address:        row.Address,
			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 collectHealthInsuranceStateNames(rows []health_insurance_companies.HealthInsuranceCompany) []string {
	out := make([]string, 0, len(rows))
	for i := range rows {
		out = append(out, rows[i].State)
	}
	return out
}

func collectHealthInsuranceLandIDs(rows []health_insurance_companies.HealthInsuranceCompany) []string {
	out := make([]string, 0, len(rows))
	for i := range rows {
		if len(rows[i].LandID) == 0 {
			continue
		}
		out = append(out, strings.ToLower(hex.EncodeToString(rows[i].LandID)))
	}
	return out
}

func resolveHealthInsuranceStateDetail(state string, details map[string]health_insurance_companies.StateDetail) health_insurance_companies.StateDetail {
	key := strings.ToLower(strings.TrimSpace(state))
	if key == "" || details == nil {
		return health_insurance_companies.StateDetail{}
	}
	return details[key]
}

func resolveHealthInsuranceLandDetail(landID []byte, details map[string]health_insurance_companies.LandDetail) health_insurance_companies.LandDetail {
	if len(landID) == 0 || details == nil {
		return health_insurance_companies.LandDetail{}
	}
	return details[strings.ToLower(hex.EncodeToString(landID))]
}

func landIDString(row *health_insurance_companies.HealthInsuranceCompany, detail health_insurance_companies.StateDetail) string {
	if row != nil && len(row.LandID) > 0 {
		return idString(row.LandID)
	}
	return detail.LandID
}

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

func inferHealthInsuranceDef(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.ErrHealthInsuranceNotFound
	case fiber.StatusConflict:
		return apperrorsx.ErrHealthInsuranceRelationDelete
	case fiber.StatusUnprocessableEntity:
		switch {
		case strings.Contains(lowerDetail, "uuid is invalid"):
			return apperrorsx.ErrHealthInsuranceInvalidUUID
		case strings.Contains(lowerDetail, "id is required"):
			return apperrorsx.ErrHealthInsuranceIDRequired
		case strings.Contains(lowerDetail, "id does not match"):
			return apperrorsx.ErrHealthInsuranceIDMismatch
		case strings.Contains(lowerDetail, "at least one attribute"):
			return apperrorsx.ErrHealthInsuranceAttributesRequired
		case strings.Contains(lowerDetail, "name is required"), strings.Contains(lowerDetail, "name cannot be empty"):
			return apperrorsx.ErrHealthInsuranceNameRequired
		case strings.Contains(lowerDetail, "land_id is invalid"):
			return apperrorsx.ErrHealthInsuranceLandIDInvalid
		default:
			return apperrorsx.ErrHealthInsuranceInvalidPayload
		}
	case fiber.StatusBadRequest:
		switch {
		case strings.Contains(lowerTitle, "invalid json"):
			return apperrorsx.ErrHealthInsuranceInvalidJSON
		case strings.Contains(lowerTitle, "create failed"):
			return apperrorsx.ErrHealthInsuranceCreateFailed
		case strings.Contains(lowerTitle, "update failed"):
			return apperrorsx.ErrHealthInsuranceUpdateFailed
		case strings.Contains(lowerTitle, "delete failed"):
			return apperrorsx.ErrHealthInsuranceDeleteFailed
		case strings.Contains(lowerTitle, "list failed"):
			return apperrorsx.ErrHealthInsuranceListFailed
		default:
			return apperrorsx.ErrHealthInsuranceInvalidPayload
		}
	default:
		return apperrorsx.ErrInternal
	}
}
