package handlers

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

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

	"wucher/internal/domain/operation"
	"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 HEMSOperationHandler struct {
	svc      operation.HEMSOperationService
	validate *validators.Validator
}

func NewHEMSOperationHandler(svc operation.HEMSOperationService) *HEMSOperationHandler {
	return &HEMSOperationHandler{svc: svc, validate: validators.New()}
}

// CreateHEMSOperation godoc
// @Summary Create HEMS operation
// @Tags Operation - HEMS Operation
// @Accept json
// @Produce json
// @Param request body dto.HEMSOperationCreateRequest true "JSON:API HEMS operation create request"
// @Success 201 {object} dto.HEMSOperationResponse
// @Failure 422 {object} dto.ErrorResponse
// @Failure 400 {object} dto.ErrorResponse
// @Router /api/v1/hems-operation/create [post]
func (h *HEMSOperationHandler) Create(c *fiber.Ctx) error {
	var req dto.HEMSOperationCreateRequest
	if err := c.BodyParser(&req); err != nil {
		return writeHEMSOperationErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{Status: "400", Title: "Invalid JSON", Detail: safeInternalDetail()}})
	}
	if errs := h.validate.ValidateStruct(req); errs != nil {
		return writeHEMSOperationErrors(c, fiber.StatusUnprocessableEntity, errs)
	}

	dt, err := time.Parse(time.RFC3339, strings.TrimSpace(req.Data.Attributes.Date))
	if err != nil {
		return writeHEMSOperationErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422", Title: "Validation error", Detail: "date must be in RFC3339 format", Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/date"},
		}})
	}

	row := &operation.HEMSOperation{Date: dt, CreatedBy: actorUserID(c), UpdatedBy: actorUserID(c)}
	if req.Data.Attributes.OperationalDataID != nil {
		parsed, errObj := parseOptionalUUID(req.Data.Attributes.OperationalDataID, "/data/attributes/operational_data_id")
		if errObj != nil {
			return writeHEMSOperationErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{*errObj})
		}
		row.OperationalDataID = parsed
	}
	if req.Data.Attributes.MissionID != nil {
		parsed, errObj := parseOptionalUUID(req.Data.Attributes.MissionID, "/data/attributes/mission_id")
		if errObj != nil {
			return writeHEMSOperationErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{*errObj})
		}
		row.MissionID = parsed
	}
	if req.Data.Attributes.HEMSOperationCategoryID != nil {
		parsed, errObj := parseOptionalUUID(req.Data.Attributes.HEMSOperationCategoryID, "/data/attributes/hems_operation_category_id")
		if errObj != nil {
			return writeHEMSOperationErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{*errObj})
		}
		row.HEMSOperationCategoryID = parsed
	}

	if err := h.svc.Create(c.UserContext(), row); err != nil {
		if status, errs, ok := mapOperationRelationError(err, map[string]relationFieldError{
			"(`operational_data_id`)":                {Pointer: "/data/attributes/operational_data_id", Detail: "operational_data_id references data that does not exist"},
			"(`hems_operation_category_id`)":         {Pointer: "/data/attributes/hems_operation_category_id", Detail: "hems_operation_category_id references data that does not exist"},
			"(`mission_id`)":                         {Pointer: "/data/attributes/mission_id", Detail: "mission_id references data that does not exist"},
			"references `hems_operational_data`":     {Pointer: "/data/attributes/operational_data_id", Detail: "operational_data_id references data that does not exist"},
			"references `hems_operation_categories`": {Pointer: "/data/attributes/hems_operation_category_id", Detail: "hems_operation_category_id references data that does not exist"},
			"references `missions`":                  {Pointer: "/data/attributes/mission_id", Detail: "mission_id references data that does not exist"},
		}); ok {
			return writeHEMSOperationErrors(c, status, errs)
		}
		return writeHEMSOperationErrors(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, hemsOperationResource(created))
	}
	return response.Write(c, fiber.StatusCreated, hemsOperationResource(row))
}

// GetHEMSOperation godoc
// @Summary Get HEMS operation by ID
// @Tags Operation - HEMS Operation
// @Produce json
// @Param uuid path string true "HEMS operation UUID (UUIDv7)"
// @Success 200 {object} dto.HEMSOperationResponse
// @Failure 422 {object} dto.ErrorResponse
// @Failure 404 {object} dto.ErrorResponse
// @Router /api/v1/hems-operation/get/{uuid} [get]
func (h *HEMSOperationHandler) Get(c *fiber.Ctx) error {
	id, err := uuidv7.ParseString(c.Params("uuid"))
	if err != nil {
		return writeHEMSOperationErrors(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 writeHEMSOperationErrors(c, fiber.StatusNotFound, []jsonapi.ErrorObject{{Status: "404", Title: "Not found", Detail: "hems operation not found"}})
	}
	return response.Write(c, fiber.StatusOK, hemsOperationResource(row))
}

// UpdateHEMSOperation godoc
// @Summary Update HEMS operation (partial)
// @Tags Operation - HEMS Operation
// @Accept json
// @Produce json
// @Param uuid path string true "HEMS operation UUID (UUIDv7)"
// @Param request body dto.HEMSOperationUpdateRequest true "JSON:API HEMS operation update request"
// @Success 200 {object} dto.HEMSOperationResponse
// @Failure 422 {object} dto.ErrorResponse
// @Failure 404 {object} dto.ErrorResponse
// @Router /api/v1/hems-operation/update/{uuid} [patch]
func (h *HEMSOperationHandler) Update(c *fiber.Ctx) error {
	id, err := uuidv7.ParseString(c.Params("uuid"))
	if err != nil {
		return writeHEMSOperationErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{Status: "422", Title: "Validation error", Detail: "uuid is invalid UUID", Source: &jsonapi.ErrorSource{Pointer: "/path/uuid"}}})
	}

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

	attrs := req.Data.Attributes
	if attrs.Date == nil && attrs.OperationalDataID == nil && attrs.MissionID == nil && attrs.HEMSOperationCategoryID == nil {
		return writeHEMSOperationErrors(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 writeHEMSOperationErrors(c, fiber.StatusNotFound, []jsonapi.ErrorObject{{Status: "404", Title: "Not found", Detail: "hems operation not found"}})
	}

	if attrs.Date != nil {
		dt, err := time.Parse(time.RFC3339, strings.TrimSpace(*attrs.Date))
		if err != nil {
			return writeHEMSOperationErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
				Status: "422", Title: "Validation error", Detail: "date must be in RFC3339 format", Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/date"},
			}})
		}
		existing.Date = dt
	}
	if attrs.OperationalDataID != nil {
		parsed, errObj := parseOptionalUUID(attrs.OperationalDataID, "/data/attributes/operational_data_id")
		if errObj != nil {
			return writeHEMSOperationErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{*errObj})
		}
		existing.OperationalDataID = parsed
	}
	if attrs.MissionID != nil {
		parsed, errObj := parseOptionalUUID(attrs.MissionID, "/data/attributes/mission_id")
		if errObj != nil {
			return writeHEMSOperationErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{*errObj})
		}
		existing.MissionID = parsed
	}
	if attrs.HEMSOperationCategoryID != nil {
		parsed, errObj := parseOptionalUUID(attrs.HEMSOperationCategoryID, "/data/attributes/hems_operation_category_id")
		if errObj != nil {
			return writeHEMSOperationErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{*errObj})
		}
		existing.HEMSOperationCategoryID = parsed
	}
	existing.UpdatedBy = actorUserID(c)

	if err := h.svc.Update(c.UserContext(), existing); err != nil {
		if status, errs, ok := mapOperationRelationError(err, map[string]relationFieldError{
			"(`operational_data_id`)":                {Pointer: "/data/attributes/operational_data_id", Detail: "operational_data_id references data that does not exist"},
			"(`hems_operation_category_id`)":         {Pointer: "/data/attributes/hems_operation_category_id", Detail: "hems_operation_category_id references data that does not exist"},
			"(`mission_id`)":                         {Pointer: "/data/attributes/mission_id", Detail: "mission_id references data that does not exist"},
			"references `hems_operational_data`":     {Pointer: "/data/attributes/operational_data_id", Detail: "operational_data_id references data that does not exist"},
			"references `hems_operation_categories`": {Pointer: "/data/attributes/hems_operation_category_id", Detail: "hems_operation_category_id references data that does not exist"},
			"references `missions`":                  {Pointer: "/data/attributes/mission_id", Detail: "mission_id references data that does not exist"},
		}); ok {
			return writeHEMSOperationErrors(c, status, errs)
		}
		return writeHEMSOperationErrors(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, hemsOperationResource(updated))
	}
	return response.Write(c, fiber.StatusOK, hemsOperationResource(existing))
}

// DeleteHEMSOperation godoc
// @Summary Delete HEMS operation
// @Tags Operation - HEMS Operation
// @Produce json
// @Param uuid path string true "HEMS operation 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/hems-operation/delete/{uuid} [delete]
func (h *HEMSOperationHandler) Delete(c *fiber.Ctx) error {
	id, err := uuidv7.ParseString(c.Params("uuid"))
	if err != nil {
		return writeHEMSOperationErrors(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 writeHEMSOperationErrors(c, fiber.StatusNotFound, []jsonapi.ErrorObject{{Status: "404", Title: "Not found", Detail: "hems operation not found"}})
		}
		if status, errs, ok := mapOperationRelationError(err, nil); ok {
			return writeHEMSOperationErrors(c, status, errs)
		}
		return writeHEMSOperationErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{Status: "400", Title: "Delete failed", Detail: safeInternalDetail()}})
	}
	return response.Write(c, fiber.StatusOK, jsonapi.Resource{Type: "hems_operation_delete", Attributes: map[string]any{"deleted": true}})
}

// ListHEMSOperation godoc
// @Summary List HEMS operations
// @Tags Operation - HEMS Operation
// @Produce json
// @Param filter[search] query string false "Search by date"
// @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.HEMSOperationListResponse
// @Router /api/v1/hems-operation/get-all [get]
func (h *HEMSOperationHandler) 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 writeHEMSOperationErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{Status: "400", Title: "List failed", Detail: safeInternalDetail()}})
	}
	data := make([]dto.HEMSOperationResource, 0, len(rows))
	for i := range rows {
		data = append(data, hemsOperationResource(&rows[i]).Data)
	}
	meta := map[string]any{"page_number": pageNumber, "page_size": pageSize, "total": total}
	return response.WriteWithMeta(c, fiber.StatusOK, data, meta)
}

// ListHEMSOperationDatatable godoc
// @Summary List HEMS operations (datatable)
// @Tags Operation - HEMS Operation
// @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.HEMSOperationDataTableResponse
// @Router /api/v1/hems-operation/get-all/dt [get]
func (h *HEMSOperationHandler) 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 writeHEMSOperationErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{Status: "400", Title: "List failed", Detail: safeInternalDetail()}})
	}
	data := make([]dto.HEMSOperationResource, 0, len(rows))
	for i := range rows {
		data = append(data, hemsOperationResource(&rows[i]).Data)
	}
	meta := map[string]any{"draw": draw, "records_total": total, "records_filtered": total}
	return response.WriteWithMeta(c, fiber.StatusOK, data, meta)
}

func hemsOperationResource(row *operation.HEMSOperation) dto.HEMSOperationResponse {
	if row == nil {
		return dto.HEMSOperationResponse{Data: dto.HEMSOperationResource{Type: "hems_operation"}}
	}
	operationalDataID := uuidStringOrEmpty(row.OperationalDataID)
	missionID := uuidStringOrEmpty(row.MissionID)
	categoryID := uuidStringOrEmpty(row.HEMSOperationCategoryID)

	var operationalData *dto.HEMSOperationOperationalDataRef
	if row.OperationalData != nil && len(row.OperationalData.ID) > 0 {
		operationalData = &dto.HEMSOperationOperationalDataRef{ID: idString(row.OperationalData.ID)}
	}
	var mission *dto.HEMSOperationMissionRef
	if row.Mission != nil && len(row.Mission.ID) > 0 {
		mission = &dto.HEMSOperationMissionRef{
			ID:       idString(row.Mission.ID),
			FlightID: uuidStringOrEmpty(row.Mission.FlightID),
			Type:     row.Mission.Type,
		}
	}
	var category *dto.HEMSOperationCategoryRef
	if row.HEMSOperationCategory != nil && len(row.HEMSOperationCategory.ID) > 0 {
		category = &dto.HEMSOperationCategoryRef{ID: idString(row.HEMSOperationCategory.ID), Name: row.HEMSOperationCategory.Name, Type: row.HEMSOperationCategory.Type}
	}

	attrs := dto.HEMSOperationAttributes{
		Date:                    row.Date.UTC().Format(time.RFC3339),
		OperationalDataID:       operationalDataID,
		MissionID:               missionID,
		HEMSOperationCategoryID: categoryID,
		OperationalData:         operationalData,
		Mission:                 mission,
		HEMSOperationCategory:   category,
		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),
	}

	return dto.HEMSOperationResponse{Data: dto.HEMSOperationResource{Type: "hems_operation", ID: idString(row.ID), Attributes: attrs}}
}

func writeHEMSOperationErrors(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 := inferHEMSOperationErrorCode(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 inferHEMSOperationErrorCode(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.CodeHEMSOperationNotFound, apperrorsx.ErrHEMSOperationNotFound.ErrorCode
	case fiber.StatusUnprocessableEntity:
		switch {
		case strings.Contains(lowerDetail, "uuid is invalid"):
			return apperrorsx.CodeHEMSOperationInvalidUUID, apperrorsx.ErrHEMSOperationInvalidUUID.ErrorCode
		case strings.Contains(lowerDetail, "at least one attribute"):
			return apperrorsx.CodeHEMSOperationAttributesRequired, apperrorsx.ErrHEMSOperationAttributesRequired.ErrorCode
		case strings.Contains(lowerDetail, "date must be in rfc3339"):
			return apperrorsx.CodeHEMSOperationDateInvalidRFC3339, apperrorsx.ErrHEMSOperationDateInvalidRFC3339.ErrorCode
		case strings.Contains(lowerDetail, "references data that does not exist"), strings.Contains(lowerDetail, "invalid uuid"):
			return apperrorsx.CodeHEMSOperationRelationReferenceInvalid, apperrorsx.ErrHEMSOperationRelationReferenceInvalid.ErrorCode
		default:
			return apperrorsx.CodeHEMSOperationInvalidPayload, apperrorsx.ErrHEMSOperationInvalidPayload.ErrorCode
		}
	case fiber.StatusBadRequest:
		switch {
		case strings.Contains(lowerTitle, "invalid json"):
			return apperrorsx.CodeHEMSOperationInvalidJSON, apperrorsx.ErrHEMSOperationInvalidJSON.ErrorCode
		case strings.Contains(lowerTitle, "create failed"):
			return apperrorsx.CodeHEMSOperationCreateFailed, apperrorsx.ErrHEMSOperationCreateFailed.ErrorCode
		case strings.Contains(lowerTitle, "update failed"):
			return apperrorsx.CodeHEMSOperationUpdateFailed, apperrorsx.ErrHEMSOperationUpdateFailed.ErrorCode
		case strings.Contains(lowerTitle, "delete failed"):
			return apperrorsx.CodeHEMSOperationDeleteFailed, apperrorsx.ErrHEMSOperationDeleteFailed.ErrorCode
		case strings.Contains(lowerTitle, "list failed"):
			return apperrorsx.CodeHEMSOperationListFailed, apperrorsx.ErrHEMSOperationListFailed.ErrorCode
		default:
			return apperrorsx.CodeInvalidRequest, apperrorsx.ErrInvalidRequest.ErrorCode
		}
	default:
		return apperrorsx.CodeInternalServerError, apperrorsx.ErrInternal.ErrorCode
	}
}
