package handlers

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

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

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

func NewInsurancePatientDataHandler(svc insurancepatientdata.Service) *InsurancePatientDataHandler {
	return &InsurancePatientDataHandler{
		svc:      svc,
		validate: validators.New(),
	}
}

// CreateInsurancePatientData godoc
// @Summary Create insurance patient data
// @Description Create an InsurancePatientData record.
// @Tags PatientData - InsurancePatientData
// @Accept json
// @Produce json
// @Param request body dto.InsurancePatientDataCreateRequest true "JSON:API InsurancePatientData create request"
// @Success 201 {object} dto.InsurancePatientDataResponse
// @Failure 422 {object} dto.ErrorResponse
// @Failure 400 {object} dto.ErrorResponse
// @Router /api/v1/insurance-patient-data/create [post]
func (h *InsurancePatientDataHandler) Create(c *fiber.Ctx) error {
	var req dto.InsurancePatientDataCreateRequest
	if err := c.BodyParser(&req); err != nil {
		return writeInsurancePatientDataErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "Invalid JSON",
			Detail: safeInternalDetail(),
		}})
	}
	if errs := h.validate.ValidateStruct(req); errs != nil {
		return writeInsurancePatientDataErrors(c, fiber.StatusUnprocessableEntity, errs)
	}

	healthInsuranceID, err := uuidv7.ParseString(strings.TrimSpace(req.Data.Attributes.HealthInsuranceCompaniesId))
	if err != nil {
		return writeInsurancePatientDataErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "health_insurance_companies_id is invalid UUID",
			Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/health_insurance_companies_id"},
		}})
	}
	federalStateID, err := uuidv7.ParseString(strings.TrimSpace(req.Data.Attributes.FederalStateId))
	if err != nil {
		return writeInsurancePatientDataErrors(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 := &insurancepatientdata.InsurancePatientData{
		HealthInsuranceCompaniesId: healthInsuranceID,
		FederalStateId:             federalStateID,
		CreatedBy:                  actorUserID(c),
		UpdatedBy:                  actorUserID(c),
	}

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

// GetInsurancePatientData godoc
// @Summary Get insurance patient data by ID
// @Description Get a single InsurancePatientData record by UUID.
// @Tags PatientData - InsurancePatientData
// @Produce json
// @Param uuid path string true "InsurancePatientData UUID (UUIDv7)"
// @Success 200 {object} dto.InsurancePatientDataResponse
// @Failure 422 {object} dto.ErrorResponse
// @Failure 404 {object} dto.ErrorResponse
// @Router /api/v1/insurance-patient-data/get/{uuid} [get]
func (h *InsurancePatientDataHandler) Get(c *fiber.Ctx) error {
	uuidStr := c.Params("uuid")
	id, err := uuidv7.ParseString(uuidStr)
	if err != nil {
		return writeInsurancePatientDataErrors(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 writeInsurancePatientDataErrors(c, fiber.StatusNotFound, []jsonapi.ErrorObject{{
			Status: "404",
			Title:  "Not found",
			Detail: "insurance patient data not found",
		}})
	}

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

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

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

	if strings.TrimSpace(req.Data.ID) == "" {
		return writeInsurancePatientDataErrors(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 writeInsurancePatientDataErrors(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.HealthInsuranceCompaniesId == nil && attrs.FederalStateId == nil {
		return writeInsurancePatientDataErrors(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 writeInsurancePatientDataErrors(c, fiber.StatusNotFound, []jsonapi.ErrorObject{{
			Status: "404",
			Title:  "Not found",
			Detail: "insurance patient data not found",
		}})
	}

	if attrs.HealthInsuranceCompaniesId != nil {
		parsed, parseErr := uuidv7.ParseString(strings.TrimSpace(*attrs.HealthInsuranceCompaniesId))
		if parseErr != nil {
			return writeInsurancePatientDataErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
				Status: "422",
				Title:  "Validation error",
				Detail: "health_insurance_companies_id is invalid UUID",
				Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/health_insurance_companies_id"},
			}})
		}
		existing.HealthInsuranceCompaniesId = parsed
	}
	if attrs.FederalStateId != nil {
		parsed, parseErr := uuidv7.ParseString(strings.TrimSpace(*attrs.FederalStateId))
		if parseErr != nil {
			return writeInsurancePatientDataErrors(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 = parsed
	}
	existing.UpdatedBy = actorUserID(c)

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

// DeleteInsurancePatientData godoc
// @Summary Delete insurance patient data
// @Description Soft delete InsurancePatientData by ID.
// @Tags PatientData - InsurancePatientData
// @Produce json
// @Param uuid path string true "InsurancePatientData UUID (UUIDv7)"
// @Success 200 {object} dto.GenericDeleteResponse
// @Failure 422 {object} dto.ErrorResponse
// @Failure 404 {object} dto.ErrorResponse
// @Failure 400 {object} dto.ErrorResponse
// @Router /api/v1/insurance-patient-data/delete/{uuid} [delete]
func (h *InsurancePatientDataHandler) Delete(c *fiber.Ctx) error {
	uuidStr := c.Params("uuid")
	id, err := uuidv7.ParseString(uuidStr)
	if err != nil {
		return writeInsurancePatientDataErrors(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 writeInsurancePatientDataErrors(c, fiber.StatusNotFound, []jsonapi.ErrorObject{{
				Status: "404",
				Title:  "Not found",
				Detail: "insurance patient data not found",
			}})
		}
		return writeInsurancePatientDataErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "Delete failed",
			Detail: safeInternalDetail(),
		}})
	}

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

// ListInsurancePatientData godoc
// @Summary List insurance patient data
// @Description JSON:API list with pagination, filtering and sorting. Sort values: created_at, -created_at, updated_at, -updated_at.
// @Tags PatientData - InsurancePatientData
// @Produce json
// @Param filter[search] query string false "Search"
// @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.InsurancePatientDataListResponse
// @Router /api/v1/insurance-patient-data/get-all [get]
func (h *InsurancePatientDataHandler) 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 writeInsurancePatientDataErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "List failed",
			Detail: safeInternalDetail(),
		}})
	}

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

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

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

// ListInsurancePatientDataDatatable godoc
// @Summary List insurance patient data (datatable)
// @Description Datatable response with simple pagination params.
// @Tags PatientData - InsurancePatientData
// @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.InsurancePatientDataDataTableResponse
// @Router /api/v1/insurance-patient-data/get-all/dt [get]
func (h *InsurancePatientDataHandler) 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 writeInsurancePatientDataErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "List failed",
			Detail: safeInternalDetail(),
		}})
	}

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

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

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

func insurancePatientDataResource(row *insurancepatientdata.InsurancePatientData) dto.InsurancePatientDataResource {
	attrs := dto.InsurancePatientDataAttributes{
		HealthInsuranceCompaniesId: idString(row.HealthInsuranceCompaniesId),
		FederalStateId:             idString(row.FederalStateId),
		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),
	}

	if row.HealthInsuranceCompanies != nil {
		attrs.HealthInsuranceCompany = &dto.InsurancePatientDataHealthInsuranceCompany{
			ID:           idString(row.HealthInsuranceCompanies.ID),
			Name:         row.HealthInsuranceCompanies.Name,
			State:        row.HealthInsuranceCompanies.State,
			Address:      row.HealthInsuranceCompanies.Address,
			MobileNumber: row.HealthInsuranceCompanies.MobileNumber,
			Email:        row.HealthInsuranceCompanies.Email,
		}
	}

	if row.FederalState != nil {
		attrs.FederalState = &dto.InsurancePatientDataFederalState{
			ID:   idString(row.FederalState.ID),
			Name: row.FederalState.Name,
		}
	}

	return dto.InsurancePatientDataResource{
		Type:       "insurance_patient_data",
		ID:         idString(row.ID),
		Attributes: attrs,
	}
}

func writeInsurancePatientDataErrors(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 := inferInsurancePatientDataDef(status, e.Title, e.Detail)
		if strings.TrimSpace(e.Code) == "" {
			e.Code = def.Code
		}
		if strings.TrimSpace(e.ErrorCode) == "" {
			e.ErrorCode = def.ErrorCode
		}
		if strings.TrimSpace(e.Title) == "" {
			e.Title = def.Title
		}
		e.Detail = def.Message
		enriched = append(enriched, e)
	}
	return response.WriteErrors(c, status, enriched)
}

func inferInsurancePatientDataDef(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.ErrInsurancePatientDataNotFound
	case fiber.StatusConflict:
		return apperrorsx.ErrInsurancePatientDataRelationDelete
	case fiber.StatusUnprocessableEntity:
		switch {
		case strings.Contains(lowerDetail, "uuid is invalid"):
			return apperrorsx.ErrInsurancePatientDataInvalidUUID
		case strings.Contains(lowerDetail, "id is required"):
			return apperrorsx.ErrInsurancePatientDataIDRequired
		case strings.Contains(lowerDetail, "id does not match"):
			return apperrorsx.ErrInsurancePatientDataIDMismatch
		case strings.Contains(lowerDetail, "at least one attribute"):
			return apperrorsx.ErrInsurancePatientDataAttributesRequired
		case strings.Contains(lowerDetail, "health_insurance_companies_id is invalid"):
			return apperrorsx.ErrInsurancePatientDataHealthInsuranceIDInvalid
		case strings.Contains(lowerDetail, "federal_state_id is invalid"):
			return apperrorsx.ErrInsurancePatientDataFederalStateIDInvalid
		default:
			return apperrorsx.ErrInsurancePatientDataInvalidPayload
		}
	case fiber.StatusBadRequest:
		switch {
		case strings.Contains(lowerTitle, "invalid json"):
			return apperrorsx.ErrInsurancePatientDataInvalidJSON
		case strings.Contains(lowerTitle, "create failed"):
			return apperrorsx.ErrInsurancePatientDataCreateFailed
		case strings.Contains(lowerTitle, "update failed"):
			return apperrorsx.ErrInsurancePatientDataUpdateFailed
		case strings.Contains(lowerTitle, "delete failed"):
			return apperrorsx.ErrInsurancePatientDataDeleteFailed
		case strings.Contains(lowerTitle, "list failed"):
			return apperrorsx.ErrInsurancePatientDataListFailed
		default:
			return apperrorsx.ErrInsurancePatientDataInvalidPayload
		}
	default:
		return apperrorsx.ErrInternal
	}
}

func inferInsurancePatientDataErrorCode(status int, title, detail string) (string, string) {
	def := inferInsurancePatientDataDef(status, title, detail)
	return def.Code, def.ErrorCode
}
