package handlers

import (
	"strconv"
	"strings"
	"time"

	"github.com/gofiber/fiber/v2"

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

func NewHospitalHandler(svc hospital.Service) *HospitalHandler {
	return &HospitalHandler{
		svc:      svc,
		validate: validators.New(),
	}
}

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

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

	row := &hospital.Hospital{
		Name:           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 err := h.svc.Create(c.UserContext(), row); err != nil {
		return apperrorsx.Write(c, mapHospitalServiceErrorWithFallback(err, apperrorsx.ErrHospitalCreateFailed))
	}

	created, err := h.svc.GetByID(c.UserContext(), row.ID)
	if err == nil && created != nil {
		return response.Write(c, fiber.StatusCreated, hospitalResource(created))
	}
	return response.Write(c, fiber.StatusCreated, hospitalResource(row))
}

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

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

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

	if attrs.Name != nil {
		v := strings.TrimSpace(*attrs.Name)
		if v == "" {
			return writeHospitalErrors(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.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 apperrorsx.Write(c, mapHospitalServiceErrorWithFallback(err, apperrorsx.ErrHospitalUpdateFailed))
	}

	updated, err := h.svc.GetByID(c.UserContext(), existing.ID)
	if err == nil && updated != nil {
		return response.Write(c, fiber.StatusOK, hospitalResource(updated))
	}
	return response.Write(c, fiber.StatusOK, hospitalResource(existing))
}

// DeleteHospital godoc
// @Summary Delete hospital
// @Tags Hospital - Hospital
// @Produce json
// @Param uuid path string true "Hospital UUID (UUIDv7)"
// @Success 200 {object} dto.GenericDeleteResponse
// @Failure 404 {object} dto.ErrorResponse
// @Router /api/v1/hospital/delete/{uuid} [delete]
func (h *HospitalHandler) Delete(c *fiber.Ctx) error {
	uuidStr := c.Params("uuid")
	id, err := uuidv7.ParseString(uuidStr)
	if err != nil {
		return writeHospitalErrors(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 {
		return apperrorsx.Write(c, mapHospitalServiceErrorWithFallback(err, apperrorsx.ErrHospitalDeleteFailed))
	}

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

// ListHospital godoc
// @Summary List hospital
// @Description JSON:API list with pagination, filtering and sorting. Sort values: name, -name, hospital_name, -hospital_name, 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 - Hospital
// @Produce json
// @Param filter[search] query string false "Search by hospital name/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.HospitalListResponse
// @Router /api/v1/hospital/get-all [get]
func (h *HospitalHandler) 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 apperrorsx.Write(c, mapHospitalServiceErrorWithFallback(err, apperrorsx.ErrHospitalListFailed))
	}

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

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

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

// ListHospitalDatatable godoc
// @Summary List hospital (datatable)
// @Description Datatable response with simple pagination params.
// @Tags Hospital - Hospital
// @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.HospitalDataTableResponse
// @Router /api/v1/hospital/get-all/dt [get]
func (h *HospitalHandler) 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 apperrorsx.Write(c, mapHospitalServiceErrorWithFallback(err, apperrorsx.ErrHospitalListFailed))
	}

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

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

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

func hospitalResource(row *hospital.Hospital) dto.HospitalResource {
	return dto.HospitalResource{
		Type: "hospital",
		ID:   idString(row.ID),
		Attributes: dto.HospitalAttributes{
			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 writeHospitalErrors(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
		if strings.TrimSpace(e.Code) == "" || strings.TrimSpace(e.ErrorCode) == "" {
			code, errorCode := inferHospitalErrorCode(status, e.Title, e.Detail)
			if strings.TrimSpace(e.Code) == "" {
				e.Code = code
			}
			if strings.TrimSpace(e.ErrorCode) == "" {
				e.ErrorCode = errorCode
			}
		}
		enriched = append(enriched, e)
	}
	return response.WriteErrors(c, status, enriched)
}

func inferHospitalErrorCode(status int, title, detail string) (string, string) {
	lowerTitle := strings.ToLower(strings.TrimSpace(title))
	lowerDetail := strings.ToLower(strings.TrimSpace(detail))

	switch status {
	case fiber.StatusNotFound:
		return apperrorsx.CodeHospitalNotFound, apperrorsx.ErrHospitalNotFound.ErrorCode
	case fiber.StatusConflict:
		return apperrorsx.CodeHospitalRelationDelete, apperrorsx.ErrHospitalRelationDelete.ErrorCode
	case fiber.StatusUnprocessableEntity:
		switch {
		case strings.Contains(lowerDetail, "uuid is invalid uuid"):
			return apperrorsx.CodeHospitalInvalidUUID, apperrorsx.ErrHospitalInvalidUUID.ErrorCode
		case strings.Contains(lowerDetail, "id is required"):
			return apperrorsx.CodeHospitalIDRequired, apperrorsx.ErrHospitalIDRequired.ErrorCode
		case strings.Contains(lowerDetail, "id does not match path uuid"):
			return apperrorsx.CodeHospitalIDMismatch, apperrorsx.ErrHospitalIDMismatch.ErrorCode
		case strings.Contains(lowerDetail, "at least one attribute must be provided"):
			return apperrorsx.CodeHospitalAttributesRequired, apperrorsx.ErrHospitalAttributesRequired.ErrorCode
		case strings.Contains(lowerDetail, "name is required"), strings.Contains(lowerDetail, "name cannot be empty"):
			return apperrorsx.CodeHospitalNameRequired, apperrorsx.ErrHospitalNameRequired.ErrorCode
		default:
			return apperrorsx.CodeHospitalInvalidPayload, apperrorsx.ErrHospitalInvalidPayload.ErrorCode
		}
	case fiber.StatusBadRequest:
		switch {
		case strings.Contains(lowerTitle, "invalid json"):
			return apperrorsx.CodeHospitalInvalidJSON, apperrorsx.ErrHospitalInvalidJSON.ErrorCode
		case strings.Contains(lowerTitle, "create failed"):
			return apperrorsx.CodeHospitalCreateFailed, apperrorsx.ErrHospitalCreateFailed.ErrorCode
		case strings.Contains(lowerTitle, "update failed"):
			return apperrorsx.CodeHospitalUpdateFailed, apperrorsx.ErrHospitalUpdateFailed.ErrorCode
		case strings.Contains(lowerTitle, "delete failed"):
			return apperrorsx.CodeHospitalDeleteFailed, apperrorsx.ErrHospitalDeleteFailed.ErrorCode
		case strings.Contains(lowerTitle, "list failed"):
			return apperrorsx.CodeHospitalListFailed, apperrorsx.ErrHospitalListFailed.ErrorCode
		default:
			return apperrorsx.CodeHospitalInvalidPayload, apperrorsx.ErrHospitalInvalidPayload.ErrorCode
		}
	default:
		return apperrorsx.CodeInternalServerError, apperrorsx.ErrInternal.ErrorCode
	}
}

func mapHospitalServiceErrorWithFallback(err error, fallback apperrorsx.Def) *apperrorsx.AppError {
	mapped := apperrorsx.Translate(apperrorsx.ModuleHospital, err)
	if mapped == nil {
		return apperrorsx.New(fallback).WithCause(err)
	}

	switch mapped.Code {
	case apperrorsx.CodeHospitalNotFound,
		apperrorsx.CodeHospitalRelationDelete,
		apperrorsx.CodeHospitalInvalidPayload:
		return mapped
	default:
		return apperrorsx.New(fallback).WithCause(err)
	}
}
