package handlers

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

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

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

func NewOpcHandler(svc opc.Service) *OpcHandler {
	return &OpcHandler{
		svc:      svc,
		validate: validators.New(),
	}
}

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

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

	row := &opc.Opc{
		Title:     title,
		SortKey:   cloneIntPointer(req.Data.Attributes.SortKey),
		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 writeOpcErrors(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, opcResource(created))
	}
	return response.Write(c, fiber.StatusCreated, opcResource(row))
}

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

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

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

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

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

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

// ListOpc godoc
// @Summary List opc
// @Description JSON:API list with pagination, filtering and sorting. Sort values: title, -title, sortkey, -sortkey, note, -note, is_active, -is_active, created_at, -created_at, updated_at, -updated_at.
// @Tags OPC - OPC
// @Produce json
// @Param filter[search] query string false "Search by title/note"
// @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.OpcListResponse
// @Router /api/v1/opc/get-all [get]
func (h *OpcHandler) 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 writeOpcErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "List failed",
			Detail: safeInternalDetail(),
		}})
	}

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

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

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

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

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

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

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

func opcResource(o *opc.Opc) dto.OpcResource {
	return dto.OpcResource{
		Type: "opc",
		ID:   idString(o.ID),
		Attributes: dto.OpcAttributes{
			Title:     o.Title,
			SortKey:   cloneIntPointer(o.SortKey),
			Note:      o.Note,
			IsActive:  o.IsActive,
			CreatedAt: o.CreatedAt.UTC().Format(time.RFC3339),
			CreatedBy: uuidStringOrEmpty(o.CreatedBy),
			UpdatedAt: o.UpdatedAt.UTC().Format(time.RFC3339),
			UpdatedBy: uuidStringOrEmpty(o.UpdatedBy),
			DeletedAt: timeStringOrEmpty(o.DeletedAt),
			DeletedBy: uuidStringOrEmpty(o.DeletedBy),
		},
	}
}

func writeOpcErrors(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
		if strings.TrimSpace(e.Code) == "" || strings.TrimSpace(e.ErrorCode) == "" {
			code, errorCode := inferOpcErrorCode(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 inferOpcErrorCode(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.CodeOPCNotFound, apperrorsx.ErrOPCNotFound.ErrorCode
	case fiber.StatusConflict:
		return apperrorsx.CodeOPCRelationDelete, apperrorsx.ErrOPCRelationDelete.ErrorCode
	case fiber.StatusUnprocessableEntity:
		switch {
		case strings.Contains(lowerDetail, "uuid is invalid"):
			return apperrorsx.CodeOPCInvalidUUID, apperrorsx.ErrOPCInvalidUUID.ErrorCode
		case strings.Contains(lowerDetail, "id is required"):
			return apperrorsx.CodeOPCIDRequired, apperrorsx.ErrOPCIDRequired.ErrorCode
		case strings.Contains(lowerDetail, "id does not match"):
			return apperrorsx.CodeOPCIDMismatch, apperrorsx.ErrOPCIDMismatch.ErrorCode
		case strings.Contains(lowerDetail, "at least one attribute"):
			return apperrorsx.CodeOPCAttributesRequired, apperrorsx.ErrOPCAttributesRequired.ErrorCode
		case strings.Contains(lowerDetail, "title is required"), strings.Contains(lowerDetail, "title cannot be empty"):
			return apperrorsx.CodeOPCTitleRequired, apperrorsx.ErrOPCTitleRequired.ErrorCode
		default:
			return apperrorsx.CodeOPCInvalidPayload, apperrorsx.ErrOPCInvalidPayload.ErrorCode
		}
	case fiber.StatusBadRequest:
		switch {
		case strings.Contains(lowerTitle, "invalid json"):
			return apperrorsx.CodeOPCInvalidJSON, apperrorsx.ErrOPCInvalidJSON.ErrorCode
		case strings.Contains(lowerTitle, "create failed"):
			return apperrorsx.CodeOPCCreateFailed, apperrorsx.ErrOPCCreateFailed.ErrorCode
		case strings.Contains(lowerTitle, "update failed"):
			return apperrorsx.CodeOPCUpdateFailed, apperrorsx.ErrOPCUpdateFailed.ErrorCode
		case strings.Contains(lowerTitle, "delete failed"):
			return apperrorsx.CodeOPCDeleteFailed, apperrorsx.ErrOPCDeleteFailed.ErrorCode
		case strings.Contains(lowerTitle, "list failed"):
			return apperrorsx.CodeOPCListFailed, apperrorsx.ErrOPCListFailed.ErrorCode
		default:
			return apperrorsx.CodeOPCInvalidPayload, apperrorsx.ErrOPCInvalidPayload.ErrorCode
		}
	default:
		return apperrorsx.CodeInternalServerError, apperrorsx.ErrInternal.ErrorCode
	}
}
