package handlers

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

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

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

func NewFacilityHandler(svc facility.Service) *FacilityHandler {
	return &FacilityHandler{
		svc:      svc,
		validate: validators.New(),
	}
}

// CreateFacility godoc
// @Summary Create facility
// @Description Create a facility row using one shared table. Flight-data SPO references now expect categories like `heslo-rope-label`, `heslo-rope-length`, `heslo-hook`, `hec-rope-label`, and `hec-rope-length`.
// @Tags Facility - Facilities
// @Accept json
// @Produce json
// @Param request body dto.FacilityCreateRequest true "JSON:API Facility create request"
// @Success 201 {object} dto.FacilityResponse
// @Failure 422 {object} dto.ErrorResponse
// @Failure 400 {object} dto.ErrorResponse
// @Router /api/v1/facilities/create [post]
func (h *FacilityHandler) Create(c *fiber.Ctx) error {
	var req dto.FacilityCreateRequest
	if err := c.BodyParser(&req); err != nil {
		return writeFacilityErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "Invalid JSON",
			Detail: safeInternalDetail(),
		}})
	}
	if errs := h.validate.ValidateStruct(req); errs != nil {
		return writeFacilityErrors(c, fiber.StatusUnprocessableEntity, errs)
	}

	category := strings.TrimSpace(req.Data.Attributes.Category)
	name := strings.TrimSpace(req.Data.Attributes.Name)
	facilityType := strings.TrimSpace(req.Data.Attributes.Type)
	if category == "" || name == "" {
		return response.WriteErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "category and name are required",
			Source: &jsonapi.ErrorSource{Pointer: "/data/attributes"},
		}})
	}

	row := &facility.Facility{
		Category:  category,
		Name:      name,
		Type:      facilityType,
		SortKey:   cloneIntPointerFacility(req.Data.Attributes.SortKey),
		Length:    strings.TrimSpace(stringOrDefault(req.Data.Attributes.Length, "")),
		Weight:    strings.TrimSpace(stringOrDefault(req.Data.Attributes.Weight, "")),
		Electric:  strings.TrimSpace(stringOrDefault(req.Data.Attributes.Electric, "")),
		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 writeFacilityErrors(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, facilityResource(created))
	}
	return response.Write(c, fiber.StatusCreated, facilityResource(row))
}

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

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

	if strings.TrimSpace(req.Data.ID) == "" {
		return writeFacilityErrors(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 writeFacilityErrors(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.Category == nil && attrs.Name == nil && attrs.Type == nil && !attrs.SortKey.Set && attrs.Length == nil && attrs.Weight == nil &&
		attrs.Electric == nil && attrs.Note == nil && attrs.IsActive == nil {
		return writeFacilityErrors(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 writeFacilityErrors(c, fiber.StatusNotFound, []jsonapi.ErrorObject{{
			Status: "404",
			Title:  "Not found",
			Detail: "facility not found",
		}})
	}

	if attrs.Category != nil {
		v := strings.TrimSpace(*attrs.Category)
		if v == "" {
			return writeFacilityErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
				Status: "422",
				Title:  "Validation error",
				Detail: "category cannot be empty",
				Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/category"},
			}})
		}
		existing.Category = v
	}
	if attrs.Name != nil {
		v := strings.TrimSpace(*attrs.Name)
		if v == "" {
			return writeFacilityErrors(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.Type != nil {
		existing.Type = strings.TrimSpace(*attrs.Type)
	}
	if attrs.SortKey.Set {
		if attrs.SortKey.Valid {
			sortKey := attrs.SortKey.Value
			existing.SortKey = &sortKey
		} else {
			existing.SortKey = nil
		}
	}
	if attrs.Length != nil {
		existing.Length = strings.TrimSpace(*attrs.Length)
	}
	if attrs.Weight != nil {
		existing.Weight = strings.TrimSpace(*attrs.Weight)
	}
	if attrs.Electric != nil {
		existing.Electric = strings.TrimSpace(*attrs.Electric)
	}
	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 writeFacilityErrors(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, facilityResource(updated))
	}
	return response.Write(c, fiber.StatusOK, facilityResource(existing))
}

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

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

// GetFacilityByID godoc
// @Summary Get facility by ID
// @Tags Facility - Facilities
// @Produce json
// @Param uuid path string true "Facility UUID (UUIDv7)"
// @Success 200 {object} dto.FacilityResponse
// @Failure 404 {object} dto.ErrorResponse
// @Router /api/v1/facilities/get/{uuid} [get]
func (h *FacilityHandler) Get(c *fiber.Ctx) error {
	uuidStr := c.Params("uuid")
	id, err := uuidv7.ParseString(uuidStr)
	if err != nil {
		return writeFacilityErrors(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 writeFacilityErrors(c, fiber.StatusNotFound, []jsonapi.ErrorObject{{
			Status: "404",
			Title:  "Not found",
			Detail: "facility not found",
		}})
	}

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

// ListFacilities godoc
// @Summary List facilities
// @Description JSON:API list with pagination, filtering and sorting. Supports one shared table with category discriminator (e.g. `heslo-rope-label`, `heslo-hook`, `hec-rope-label`).
// @Tags Facility - Facilities
// @Produce json
// @Param search query string false "Search by name/type/length/weight"
// @Param category query string false "Filter by category (e.g. heslo-rope-label, heslo-hook, hec-rope-label)"
// @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 sort query string false "Sort order"
// @Success 200 {object} dto.FacilityListResponse
// @Router /api/v1/facilities/get-all [get]
func (h *FacilityHandler) List(c *fiber.Ctx) error {
	filter := c.Query("search")
	category := strings.TrimSpace(c.Query("category"))

	pageNumber := parseIntDefault(c.Query("page"), 1)
	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, category, sort, 0, 0)
	if err != nil {
		return writeFacilityErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "List failed",
			Detail: safeInternalDetail(),
		}})
	}

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

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

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

// ListFacilitiesDatatable godoc
// @Summary List facilities (datatable)
// @Description Datatable response with simple pagination params.
// @Tags Facility - Facilities
// @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"
// @Param category query string false "Facility category"
// @Success 200 {object} dto.FacilityDataTableResponse
// @Router /api/v1/facilities/get-all/dt [get]
func (h *FacilityHandler) 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")
	category := strings.TrimSpace(c.Query("category"))

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

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

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

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

func facilityResource(f *facility.Facility) dto.FacilityResource {
	id, _ := uuidv7.BytesToString(f.ID)
	return dto.FacilityResource{
		Type: "facility",
		ID:   id,
		Attributes: dto.FacilityAttributes{
			Category:  f.Category,
			Name:      f.Name,
			Type:      f.Type,
			SortKey:   cloneIntPointerFacility(f.SortKey),
			Length:    f.Length,
			Weight:    f.Weight,
			Electric:  f.Electric,
			Note:      f.Note,
			IsActive:  f.IsActive,
			CreatedBy: uuidStringOrEmpty(f.CreatedBy),
			UpdatedBy: uuidStringOrEmpty(f.UpdatedBy),
			CreatedAt: f.CreatedAt.UTC().Format(time.RFC3339),
			UpdatedAt: f.UpdatedAt.UTC().Format(time.RFC3339),
		},
	}
}

func cloneIntPointerFacility(v *int) *int {
	if v == nil {
		return nil
	}
	copied := *v
	return &copied
}

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

func inferFacilityDef(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.ErrFacilityNotFound
	case fiber.StatusConflict:
		return apperrorsx.ErrFacilityRelationDelete
	case fiber.StatusUnprocessableEntity:
		switch {
		case strings.Contains(lowerDetail, "uuid is invalid uuid"), strings.Contains(lowerDetail, "invalid uuid"):
			return apperrorsx.ErrFacilityInvalidUUID
		case strings.Contains(lowerDetail, "at least one attribute must be provided"):
			return apperrorsx.ErrFacilityAttributesRequired
		case strings.Contains(lowerDetail, "category"):
			return apperrorsx.ErrFacilityCategoryRequired
		case strings.Contains(lowerDetail, "name"):
			return apperrorsx.ErrFacilityNameRequired
		case strings.Contains(lowerDetail, "type"):
			return apperrorsx.ErrFacilityTypeRequired
		default:
			return apperrorsx.ErrFacilityInvalidPayload
		}
	case fiber.StatusBadRequest:
		switch {
		case strings.Contains(lowerTitle, "invalid json"):
			return apperrorsx.ErrFacilityInvalidJSON
		case strings.Contains(lowerTitle, "create failed"):
			return apperrorsx.ErrFacilityCreateFailed
		case strings.Contains(lowerTitle, "update failed"):
			return apperrorsx.ErrFacilityUpdateFailed
		case strings.Contains(lowerTitle, "delete failed"):
			return apperrorsx.ErrFacilityDeleteFailed
		case strings.Contains(lowerTitle, "list failed"):
			return apperrorsx.ErrFacilityListFailed
		default:
			return apperrorsx.ErrFacilityInvalidPayload
		}
	default:
		return apperrorsx.ErrInternal
	}
}
