package handlers

import (
	"context"
	"errors"
	"strings"
	"time"

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

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

func NewMedicineHandler(svc medicine.Service) *MedicineHandler {
	return &MedicineHandler{
		svc:      svc,
		validate: validators.New(),
	}
}

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

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

	row := &medicine.Medicine{
		Name:      name,
		SortKey:   cloneIntPointer(req.Data.Attributes.SortKey),
		Note:      strings.TrimSpace(stringOrDefault(req.Data.Attributes.Note, "")),
		Pack:      strings.TrimSpace(stringOrDefault(req.Data.Attributes.Pack, "")),
		Unit:      strings.TrimSpace(stringOrDefault(req.Data.Attributes.Unit, "")),
		Column:    intOrDefault64(req.Data.Attributes.Column, 0),
		IsActive:  boolOrDefault(req.Data.Attributes.IsActive, true),
		CreatedBy: actorUserID(c),
		UpdatedBy: actorUserID(c),
	}
	if req.Data.Attributes.MedicineGroupID != nil && strings.TrimSpace(*req.Data.Attributes.MedicineGroupID) != "" {
		groupID, err := uuidv7.ParseString(strings.TrimSpace(*req.Data.Attributes.MedicineGroupID))
		if err != nil {
			return writeMedicineErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
				Status: "422",
				Title:  "Validation error",
				Detail: "medicine_group_id is invalid UUID",
				Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/medicine_group_id"},
			}})
		}
		row.MedicineGroupID = groupID
	}
	if req.Data.Attributes.MotorReactionID != nil && strings.TrimSpace(*req.Data.Attributes.MotorReactionID) != "" {
		reactionID, err := uuidv7.ParseString(strings.TrimSpace(*req.Data.Attributes.MotorReactionID))
		if err != nil {
			return writeMedicineErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
				Status: "422",
				Title:  "Validation error",
				Detail: "motor_reaction_id is invalid UUID",
				Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/motor_reaction_id"},
			}})
		}
		row.MotorReactionID = reactionID
	}
	reactionIDs, err := parseReactionIDs(req.Data.Attributes.MotorReactionIDs)
	if err != nil {
		return writeMedicineErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "motor_reaction_ids contains invalid UUID",
			Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/motor_reaction_ids"},
		}})
	}
	if len(reactionIDs) > 0 {
		row.MotorReactions = make([]medicine.MotorReaction, 0, len(reactionIDs))
		for i := range reactionIDs {
			row.MotorReactions = append(row.MotorReactions, medicine.MotorReaction{ID: reactionIDs[i]})
		}
	}

	if err := h.svc.Create(c.UserContext(), row); err != nil {
		return writeMedicineErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "Create failed",
			Detail: "an internal error occurred",
		}})
	}

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

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

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

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

	if attrs.Name != nil {
		v := strings.TrimSpace(*attrs.Name)
		if v == "" {
			return writeMedicineErrors(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.Note != nil {
		existing.Note = strings.TrimSpace(*attrs.Note)
	}
	if attrs.Pack != nil {
		existing.Pack = strings.TrimSpace(*attrs.Pack)
	}
	if attrs.Unit != nil {
		existing.Unit = strings.TrimSpace(*attrs.Unit)
	}
	if attrs.Column != nil {
		existing.Column = *attrs.Column
	}
	if attrs.MedicineGroupID.Set {
		// Prevent stale preloaded association from overriding FK on save.
		existing.MedicineGroup = nil
		if attrs.MedicineGroupID.Valid {
			groupIDStr := strings.TrimSpace(attrs.MedicineGroupID.Value)
			if groupIDStr == "" {
				existing.MedicineGroupID = nil
			} else {
				groupID, err := uuidv7.ParseString(groupIDStr)
				if err != nil {
					return writeMedicineErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
						Status: "422",
						Title:  "Validation error",
						Detail: "medicine_group_id is invalid UUID",
						Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/medicine_group_id"},
					}})
				}
				existing.MedicineGroupID = groupID
			}
		} else {
			existing.MedicineGroupID = nil
		}
	}
	if attrs.MotorReactionID.Set {
		// Prevent stale preloaded association from overriding FK on save.
		existing.MotorReaction = nil
		if attrs.MotorReactionID.Valid {
			reactionIDStr := strings.TrimSpace(attrs.MotorReactionID.Value)
			if reactionIDStr == "" {
				existing.MotorReactionID = nil
			} else {
				reactionID, err := uuidv7.ParseString(reactionIDStr)
				if err != nil {
					return writeMedicineErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
						Status: "422",
						Title:  "Validation error",
						Detail: "motor_reaction_id is invalid UUID",
						Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/motor_reaction_id"},
					}})
				}
				existing.MotorReactionID = reactionID
			}
		} else {
			existing.MotorReactionID = nil
		}
	}
	if attrs.MotorReactionIDs != nil {
		reactionIDs, err := parseReactionIDs(attrs.MotorReactionIDs)
		if err != nil {
			return writeMedicineErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
				Status: "422",
				Title:  "Validation error",
				Detail: "motor_reaction_ids contains invalid UUID",
				Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/motor_reaction_ids"},
			}})
		}
		existing.MotorReactions = make([]medicine.MotorReaction, 0, len(reactionIDs))
		for i := range reactionIDs {
			existing.MotorReactions = append(existing.MotorReactions, medicine.MotorReaction{ID: reactionIDs[i]})
		}
	}
	if attrs.IsActive != nil {
		existing.IsActive = *attrs.IsActive
	}
	existing.UpdatedBy = actorUserID(c)

	if err := h.svc.Update(c.UserContext(), existing); err != nil {
		return writeMedicineErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "Update failed",
			Detail: "an internal error occurred",
		}})
	}

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

// DeleteMedicine godoc
// @Summary Delete medicine
// @Tags OPC - Medicine
// @Produce json
// @Param uuid path string true "Medicine UUID (UUIDv7)"
// @Success 200 {object} dto.GenericDeleteResponse
// @Failure 404 {object} dto.ErrorResponse
// @Router /api/v1/medicine/delete/{uuid} [delete]
func (h *MedicineHandler) Delete(c *fiber.Ctx) error {
	uuidStr := c.Params("uuid")
	id, err := uuidv7.ParseString(uuidStr)
	if err != nil {
		return writeMedicineErrors(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 writeMedicineErrors(c, fiber.StatusNotFound, []jsonapi.ErrorObject{{Status: "404", Title: "Not found", Detail: "medicine not found"}})
		}
		if _, ok := apperrors.AsDeleteConflict(err); ok {
			return writeMedicineErrors(c, fiber.StatusConflict, []jsonapi.ErrorObject{{Status: "409", Title: "Conflict", Detail: "an internal error occurred"}})
		}
		return writeMedicineErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{Status: "400", Title: "Delete failed", Detail: "an internal error occurred"}})
	}

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

// ListMedicine godoc
// @Summary List medicine
// @Description JSON:API list with pagination, filtering and sorting. Search covers name, note, pack, unit, and column. Sort values: name, -name, sortkey, -sortkey, note, -note, pack, -pack, unit, -unit, column, -column, is_active, -is_active, created_at, -created_at, updated_at, -updated_at.
// @Tags OPC - Medicine
// @Produce json
// @Param filter[search] query string false "Search by name/note/pack/unit/column"
// @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.MedicineListResponse
// @Router /api/v1/medicine/get-all [get]
func (h *MedicineHandler) 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 writeMedicineErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "List failed",
			Detail: "an internal error occurred",
		}})
	}

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

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

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

// ListMedicineDatatable godoc
// @Summary List medicine (datatable)
// @Description Datatable response with simple pagination params.
// @Tags OPC - Medicine
// @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.MedicineDataTableResponse
// @Router /api/v1/medicine/get-all/dt [get]
func (h *MedicineHandler) 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 writeMedicineErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "List failed",
			Detail: "an internal error occurred",
		}})
	}

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

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

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

func medicineResource(row *medicine.Medicine) dto.MedicineResource {
	var groupResource *dto.MedicineGroupResource
	var motorReactionResource *dto.MotorReactionResource
	if row.MedicineGroup != nil {
		g := groupResourceFromMedicine(row.MedicineGroup)
		groupResource = &g
	}
	if row.MotorReaction != nil {
		r := reactionResourceFromMedicine(row.MotorReaction)
		motorReactionResource = &r
	}
	motorReactions := make([]dto.MotorReactionResource, 0, len(row.MotorReactions))
	for i := range row.MotorReactions {
		motorReactions = append(motorReactions, reactionResourceFromMedicine(&row.MotorReactions[i]))
	}
	motorReactionIDs := make([]string, 0, len(row.MotorReactions))
	for i := range row.MotorReactions {
		motorReactionIDs = append(motorReactionIDs, idString(row.MotorReactions[i].ID))
	}
	if len(motorReactionIDs) == 0 && len(row.MotorReactionID) > 0 {
		motorReactionIDs = []string{idString(row.MotorReactionID)}
	}
	return dto.MedicineResource{
		Type: "medicine",
		ID:   idString(row.ID),
		Attributes: dto.MedicineAttributes{
			Name:             row.Name,
			SortKey:          cloneIntPointer(row.SortKey),
			Note:             row.Note,
			Pack:             row.Pack,
			Unit:             row.Unit,
			Column:           row.Column,
			MedicineGroupID:  idString(row.MedicineGroupID),
			MotorReactionID:  idString(row.MotorReactionID),
			MotorReactionIDs: motorReactionIDs,
			MedicineGroup:    groupResource,
			MotorReaction:    motorReactionResource,
			MotorReactions:   motorReactions,
			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 parseReactionIDs(in []string) ([][]byte, error) {
	ids := make([][]byte, 0, len(in))
	seen := make(map[string]struct{}, len(in))
	for i := range in {
		raw := strings.TrimSpace(in[i])
		if raw == "" {
			continue
		}
		id, err := uuidv7.ParseString(raw)
		if err != nil {
			return nil, err
		}
		key := string(id)
		if _, ok := seen[key]; ok {
			continue
		}
		seen[key] = struct{}{}
		ids = append(ids, id)
	}
	return ids, nil
}

func reactionResourceFromMedicine(row *medicine.MotorReaction) dto.MotorReactionResource {
	return dto.MotorReactionResource{
		Type: "motor_reaction",
		ID:   idString(row.ID),
		Attributes: dto.MotorReactionAttributes{
			Name:      row.Name,
			Score:     row.Score,
			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 groupResourceFromMedicine(row *medicine.MedicineGroup) dto.MedicineGroupResource {
	return dto.MedicineGroupResource{
		Type: "medicine_group",
		ID:   idString(row.ID),
		Attributes: dto.MedicineGroupAttributes{
			Name:      row.Name,
			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 intOrDefault64(v *int64, def int64) int64 {
	if v == nil {
		return def
	}
	return *v
}

type medicineGroupService interface {
	CreateGroup(context.Context, *medicine.MedicineGroup) error
	UpdateGroup(context.Context, *medicine.MedicineGroup) error
	DeleteGroup(context.Context, []byte, []byte) error
	GetGroupByID(context.Context, []byte) (*medicine.MedicineGroup, error)
	ListGroups(context.Context, string, string, int, int) ([]medicine.MedicineGroup, int64, error)
}

type motorReactionService interface {
	CreateReaction(context.Context, *medicine.MotorReaction) error
	UpdateReaction(context.Context, *medicine.MotorReaction) error
	DeleteReaction(context.Context, []byte, []byte) error
	GetReactionByID(context.Context, []byte) (*medicine.MotorReaction, error)
	ListReactions(context.Context, string, string, int, int) ([]medicine.MotorReaction, int64, error)
}

func (h *MedicineHandler) groupSvc() (medicineGroupService, error) {
	svc, ok := h.svc.(medicineGroupService)
	if !ok {
		return nil, fiber.NewError(fiber.StatusServiceUnavailable, "medicine group service is not configured")
	}
	return svc, nil
}

func (h *MedicineHandler) reactionSvc() (motorReactionService, error) {
	svc, ok := h.svc.(motorReactionService)
	if !ok {
		return nil, fiber.NewError(fiber.StatusServiceUnavailable, "motor reaction service is not configured")
	}
	return svc, nil
}

// CreateMedicineGroup godoc
// @Summary Create medicine group
// @Description Create a medicine group row.
// @Tags OPC - Medicine Group
// @Accept json
// @Produce json
// @Param request body dto.MedicineGroupCreateRequest true "JSON:API medicine group create request"
// @Success 201 {object} dto.MedicineGroupResponse
// @Failure 422 {object} dto.ErrorResponse
// @Failure 400 {object} dto.ErrorResponse
// @Failure 503 {object} dto.ErrorResponse
// @Router /api/v1/medicine-group/create [post]
func (h *MedicineHandler) CreateGroup(c *fiber.Ctx) error {
	var req dto.MedicineGroupCreateRequest
	if err := c.BodyParser(&req); err != nil {
		return writeMedicineErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{Status: "400", Title: "Invalid JSON", Detail: "an internal error occurred"}})
	}
	if errs := h.validate.ValidateStruct(req); errs != nil {
		return writeMedicineErrors(c, fiber.StatusUnprocessableEntity, errs)
	}
	name := strings.TrimSpace(req.Data.Attributes.Name)
	if name == "" {
		return writeMedicineErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{Status: "422", Title: "Validation error", Detail: "name is required", Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/name"}}})
	}
	svc, err := h.groupSvc()
	if err != nil {
		return writeMedicineErrors(c, fiber.StatusServiceUnavailable, []jsonapi.ErrorObject{{Status: "503", Title: "Service unavailable", Detail: "an internal error occurred"}})
	}
	row := &medicine.MedicineGroup{Name: name, CreatedBy: actorUserID(c), UpdatedBy: actorUserID(c)}
	if err := svc.CreateGroup(c.UserContext(), row); err != nil {
		return writeMedicineErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{Status: "400", Title: "Create failed", Detail: "an internal error occurred"}})
	}
	created, _ := svc.GetGroupByID(c.UserContext(), row.ID)
	if created != nil {
		return response.Write(c, fiber.StatusCreated, groupResource(created))
	}
	return response.Write(c, fiber.StatusCreated, groupResource(row))
}

// UpdateMedicineGroup godoc
// @Summary Update medicine group (partial)
// @Description Patch medicine group by ID.
// @Tags OPC - Medicine Group
// @Accept json
// @Produce json
// @Param uuid path string true "Medicine Group UUID (UUIDv7)"
// @Param request body dto.MedicineGroupUpdateRequest true "JSON:API medicine group update request"
// @Success 200 {object} dto.MedicineGroupResponse
// @Failure 422 {object} dto.ErrorResponse
// @Failure 404 {object} dto.ErrorResponse
// @Failure 400 {object} dto.ErrorResponse
// @Failure 503 {object} dto.ErrorResponse
// @Router /api/v1/medicine-group/update/{uuid} [patch]
func (h *MedicineHandler) UpdateGroup(c *fiber.Ctx) error {
	id, err := uuidv7.ParseString(c.Params("uuid"))
	if err != nil {
		return writeMedicineErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{Status: "422", Title: "Validation error", Detail: "uuid is invalid UUID", Source: &jsonapi.ErrorSource{Pointer: "/path/uuid"}}})
	}
	var req dto.MedicineGroupUpdateRequest
	if err := c.BodyParser(&req); err != nil {
		return writeMedicineErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{Status: "400", Title: "Invalid JSON", Detail: "an internal error occurred"}})
	}
	if errs := h.validate.ValidateStruct(req); errs != nil {
		return writeMedicineErrors(c, fiber.StatusUnprocessableEntity, errs)
	}
	svc, svcErr := h.groupSvc()
	if svcErr != nil {
		return writeMedicineErrors(c, fiber.StatusServiceUnavailable, []jsonapi.ErrorObject{{Status: "503", Title: "Service unavailable", Detail: svcErr.Error()}})
	}
	row, err := svc.GetGroupByID(c.UserContext(), id)
	if err != nil || row == nil {
		return writeMedicineErrors(c, fiber.StatusNotFound, []jsonapi.ErrorObject{{Status: "404", Title: "Not found", Detail: "medicine group not found"}})
	}
	if req.Data.Attributes.Name != nil {
		name := strings.TrimSpace(*req.Data.Attributes.Name)
		if name == "" {
			return writeMedicineErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{Status: "422", Title: "Validation error", Detail: "name cannot be empty", Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/name"}}})
		}
		row.Name = name
	}
	row.UpdatedBy = actorUserID(c)
	if err := svc.UpdateGroup(c.UserContext(), row); err != nil {
		return writeMedicineErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{Status: "400", Title: "Update failed", Detail: "an internal error occurred"}})
	}
	updated, _ := svc.GetGroupByID(c.UserContext(), row.ID)
	if updated != nil {
		return response.Write(c, fiber.StatusOK, groupResource(updated))
	}
	return response.Write(c, fiber.StatusOK, groupResource(row))
}

// DeleteMedicineGroup godoc
// @Summary Delete medicine group
// @Tags OPC - Medicine Group
// @Produce json
// @Param uuid path string true "Medicine Group UUID (UUIDv7)"
// @Success 200 {object} dto.GenericDeleteResponse
// @Failure 404 {object} dto.ErrorResponse
// @Failure 422 {object} dto.ErrorResponse
// @Failure 503 {object} dto.ErrorResponse
// @Router /api/v1/medicine-group/delete/{uuid} [delete]
func (h *MedicineHandler) DeleteGroup(c *fiber.Ctx) error {
	id, err := uuidv7.ParseString(c.Params("uuid"))
	if err != nil {
		return writeMedicineErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{Status: "422", Title: "Validation error", Detail: "uuid is invalid UUID", Source: &jsonapi.ErrorSource{Pointer: "/path/uuid"}}})
	}
	svc, svcErr := h.groupSvc()
	if svcErr != nil {
		return writeMedicineErrors(c, fiber.StatusServiceUnavailable, []jsonapi.ErrorObject{{Status: "503", Title: "Service unavailable", Detail: svcErr.Error()}})
	}
	if err := svc.DeleteGroup(c.UserContext(), id, actorUserID(c)); err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return writeMedicineErrors(c, fiber.StatusNotFound, []jsonapi.ErrorObject{{Status: "404", Title: "Not found", Detail: "medicine group not found"}})
		}
		if _, ok := apperrors.AsDeleteConflict(err); ok {
			return writeMedicineErrors(c, fiber.StatusConflict, []jsonapi.ErrorObject{{Status: "409", Title: "Conflict", Detail: "an internal error occurred"}})
		}
		return writeMedicineErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{Status: "400", Title: "Delete failed", Detail: "an internal error occurred"}})
	}
	return response.Write(c, fiber.StatusOK, jsonapi.Resource{Type: "medicine_group_delete", Attributes: map[string]any{"deleted": true}})
}

// ListMedicineGroups godoc
// @Summary List medicine groups
// @Description JSON:API list with pagination, filtering and sorting. Sort values: name, -name, created_at, -created_at, updated_at, -updated_at.
// @Tags OPC - Medicine Group
// @Produce json
// @Param filter[search] query string false "Search by group name"
// @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.MedicineGroupListResponse
// @Failure 400 {object} dto.ErrorResponse
// @Failure 503 {object} dto.ErrorResponse
// @Router /api/v1/medicine-group/get-all [get]
func (h *MedicineHandler) ListGroups(c *fiber.Ctx) error {
	svc, err := h.groupSvc()
	if err != nil {
		return writeMedicineErrors(c, fiber.StatusServiceUnavailable, []jsonapi.ErrorObject{{Status: "503", Title: "Service unavailable", Detail: "an internal error occurred"}})
	}
	pageNumber := parseIntDefault(c.Query("page[number]"), parseIntDefault(c.Query("page"), 1))
	if pageNumber < 1 {
		pageNumber = 1
	}
	pageSize := parseIntDefault(c.Query("page[size]"), parseIntDefault(c.Query("limit"), parseIntDefault(c.Query("size"), 20)))
	if pageSize < 1 {
		pageSize = 20
	}
	if pageSize > 100 {
		pageSize = 100
	}
	filter := c.Query("filter[search]")
	if filter == "" {
		filter = c.Query("search")
	}
	rows, total, listErr := svc.ListGroups(c.UserContext(), filter, c.Query("sort"), pageSize, (pageNumber-1)*pageSize)
	if listErr != nil {
		return writeMedicineErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{Status: "400", Title: "List failed", Detail: listErr.Error()}})
	}
	data := make([]dto.MedicineGroupResource, 0, len(rows))
	for i := range rows {
		data = append(data, groupResource(&rows[i]))
	}
	return response.WriteWithMeta(c, fiber.StatusOK, data, map[string]any{"total": total})
}

// ListMedicineGroupsDatatable godoc
// @Summary List medicine groups (datatable)
// @Description Datatable response with simple pagination params.
// @Tags OPC - Medicine Group
// @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.MedicineGroupDataTableResponse
// @Failure 400 {object} dto.ErrorResponse
// @Failure 503 {object} dto.ErrorResponse
// @Router /api/v1/medicine-group/get-all/dt [get]
func (h *MedicineHandler) ListGroupsDatatable(c *fiber.Ctx) error {
	svc, err := h.groupSvc()
	if err != nil {
		return writeMedicineErrors(c, fiber.StatusServiceUnavailable, []jsonapi.ErrorObject{{Status: "503", Title: "Service unavailable", Detail: "an internal error occurred"}})
	}
	pageNumber := parseIntDefault(c.Query("page"), 1)
	if pageNumber < 1 {
		pageNumber = 1
	}
	size := parseIntDefault(c.Query("limit"), parseIntDefault(c.Query("size"), 20))
	if size < 1 {
		size = 20
	}
	if size > 100 {
		size = 100
	}
	rows, total, listErr := svc.ListGroups(c.UserContext(), c.Query("search"), "", size, (pageNumber-1)*size)
	if listErr != nil {
		return writeMedicineErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{Status: "400", Title: "List failed", Detail: listErr.Error()}})
	}
	data := make([]dto.MedicineGroupResource, 0, len(rows))
	for i := range rows {
		data = append(data, groupResource(&rows[i]))
	}
	return response.WriteWithMeta(c, fiber.StatusOK, data, map[string]any{"draw": parseIntDefault(c.Query("draw"), pageNumber), "records_total": total, "records_filtered": total})
}

// CreateMotorReaction godoc
// @Summary Create motor reaction
// @Description Create a motor reaction row.
// @Tags OPC - Motor Reaction
// @Accept json
// @Produce json
// @Param request body dto.MotorReactionCreateRequest true "JSON:API motor reaction create request"
// @Success 201 {object} dto.MotorReactionResponse
// @Failure 422 {object} dto.ErrorResponse
// @Failure 400 {object} dto.ErrorResponse
// @Failure 503 {object} dto.ErrorResponse
// @Router /api/v1/motor-reaction/create [post]
func (h *MedicineHandler) CreateReaction(c *fiber.Ctx) error {
	var req dto.MotorReactionCreateRequest
	if err := c.BodyParser(&req); err != nil {
		return writeMedicineErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{Status: "400", Title: "Invalid JSON", Detail: "an internal error occurred"}})
	}
	if errs := h.validate.ValidateStruct(req); errs != nil {
		return writeMedicineErrors(c, fiber.StatusUnprocessableEntity, errs)
	}
	name := strings.TrimSpace(req.Data.Attributes.Name)
	if name == "" {
		return writeMedicineErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{Status: "422", Title: "Validation error", Detail: "name is required", Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/name"}}})
	}
	svc, err := h.reactionSvc()
	if err != nil {
		return writeMedicineErrors(c, fiber.StatusServiceUnavailable, []jsonapi.ErrorObject{{Status: "503", Title: "Service unavailable", Detail: "an internal error occurred"}})
	}
	row := &medicine.MotorReaction{Name: name, Score: req.Data.Attributes.Score, CreatedBy: actorUserID(c), UpdatedBy: actorUserID(c)}
	if err := svc.CreateReaction(c.UserContext(), row); err != nil {
		return writeMedicineErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{Status: "400", Title: "Create failed", Detail: "an internal error occurred"}})
	}
	created, _ := svc.GetReactionByID(c.UserContext(), row.ID)
	if created != nil {
		return response.Write(c, fiber.StatusCreated, reactionResource(created))
	}
	return response.Write(c, fiber.StatusCreated, reactionResource(row))
}

// UpdateMotorReaction godoc
// @Summary Update motor reaction (partial)
// @Description Patch motor reaction by ID.
// @Tags OPC - Motor Reaction
// @Accept json
// @Produce json
// @Param uuid path string true "Motor Reaction UUID (UUIDv7)"
// @Param request body dto.MotorReactionUpdateRequest true "JSON:API motor reaction update request"
// @Success 200 {object} dto.MotorReactionResponse
// @Failure 422 {object} dto.ErrorResponse
// @Failure 404 {object} dto.ErrorResponse
// @Failure 400 {object} dto.ErrorResponse
// @Failure 503 {object} dto.ErrorResponse
// @Router /api/v1/motor-reaction/update/{uuid} [patch]
func (h *MedicineHandler) UpdateReaction(c *fiber.Ctx) error {
	id, err := uuidv7.ParseString(c.Params("uuid"))
	if err != nil {
		return writeMedicineErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{Status: "422", Title: "Validation error", Detail: "uuid is invalid UUID", Source: &jsonapi.ErrorSource{Pointer: "/path/uuid"}}})
	}
	var req dto.MotorReactionUpdateRequest
	if err := c.BodyParser(&req); err != nil {
		return writeMedicineErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{Status: "400", Title: "Invalid JSON", Detail: "an internal error occurred"}})
	}
	if errs := h.validate.ValidateStruct(req); errs != nil {
		return writeMedicineErrors(c, fiber.StatusUnprocessableEntity, errs)
	}
	svc, svcErr := h.reactionSvc()
	if svcErr != nil {
		return writeMedicineErrors(c, fiber.StatusServiceUnavailable, []jsonapi.ErrorObject{{Status: "503", Title: "Service unavailable", Detail: svcErr.Error()}})
	}
	row, err := svc.GetReactionByID(c.UserContext(), id)
	if err != nil || row == nil {
		return writeMedicineErrors(c, fiber.StatusNotFound, []jsonapi.ErrorObject{{Status: "404", Title: "Not found", Detail: "motor reaction not found"}})
	}
	if req.Data.Attributes.Name != nil {
		name := strings.TrimSpace(*req.Data.Attributes.Name)
		if name == "" {
			return writeMedicineErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{Status: "422", Title: "Validation error", Detail: "name cannot be empty", Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/name"}}})
		}
		row.Name = name
	}
	if req.Data.Attributes.Score.Set {
		if req.Data.Attributes.Score.Valid {
			score := req.Data.Attributes.Score.Value
			row.Score = &score
		} else {
			row.Score = nil
		}
	}
	row.UpdatedBy = actorUserID(c)
	if err := svc.UpdateReaction(c.UserContext(), row); err != nil {
		return writeMedicineErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{Status: "400", Title: "Update failed", Detail: "an internal error occurred"}})
	}
	updated, _ := svc.GetReactionByID(c.UserContext(), row.ID)
	if updated != nil {
		return response.Write(c, fiber.StatusOK, reactionResource(updated))
	}
	return response.Write(c, fiber.StatusOK, reactionResource(row))
}

// DeleteMotorReaction godoc
// @Summary Delete motor reaction
// @Tags OPC - Motor Reaction
// @Produce json
// @Param uuid path string true "Motor Reaction UUID (UUIDv7)"
// @Success 200 {object} dto.GenericDeleteResponse
// @Failure 404 {object} dto.ErrorResponse
// @Failure 422 {object} dto.ErrorResponse
// @Failure 503 {object} dto.ErrorResponse
// @Router /api/v1/motor-reaction/delete/{uuid} [delete]
func (h *MedicineHandler) DeleteReaction(c *fiber.Ctx) error {
	id, err := uuidv7.ParseString(c.Params("uuid"))
	if err != nil {
		return writeMedicineErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{Status: "422", Title: "Validation error", Detail: "uuid is invalid UUID", Source: &jsonapi.ErrorSource{Pointer: "/path/uuid"}}})
	}
	svc, svcErr := h.reactionSvc()
	if svcErr != nil {
		return writeMedicineErrors(c, fiber.StatusServiceUnavailable, []jsonapi.ErrorObject{{Status: "503", Title: "Service unavailable", Detail: svcErr.Error()}})
	}
	if err := svc.DeleteReaction(c.UserContext(), id, actorUserID(c)); err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return writeMedicineErrors(c, fiber.StatusNotFound, []jsonapi.ErrorObject{{Status: "404", Title: "Not found", Detail: "motor reaction not found"}})
		}
		if _, ok := apperrors.AsDeleteConflict(err); ok {
			return writeMedicineErrors(c, fiber.StatusConflict, []jsonapi.ErrorObject{{Status: "409", Title: "Conflict", Detail: "an internal error occurred"}})
		}
		return writeMedicineErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{Status: "400", Title: "Delete failed", Detail: "an internal error occurred"}})
	}
	return response.Write(c, fiber.StatusOK, jsonapi.Resource{Type: "motor_reaction_delete", Attributes: map[string]any{"deleted": true}})
}

// ListMotorReactions godoc
// @Summary List motor reactions
// @Description JSON:API list with pagination, filtering and sorting. Sort values: name, -name, score, -score, created_at, -created_at, updated_at, -updated_at.
// @Tags OPC - Motor Reaction
// @Produce json
// @Param filter[search] query string false "Search by reaction name or score"
// @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.MotorReactionListResponse
// @Failure 400 {object} dto.ErrorResponse
// @Failure 503 {object} dto.ErrorResponse
// @Router /api/v1/motor-reaction/get-all [get]
func (h *MedicineHandler) ListReactions(c *fiber.Ctx) error {
	svc, err := h.reactionSvc()
	if err != nil {
		return writeMedicineErrors(c, fiber.StatusServiceUnavailable, []jsonapi.ErrorObject{{Status: "503", Title: "Service unavailable", Detail: "an internal error occurred"}})
	}
	pageNumber := parseIntDefault(c.Query("page[number]"), parseIntDefault(c.Query("page"), 1))
	if pageNumber < 1 {
		pageNumber = 1
	}
	pageSize := parseIntDefault(c.Query("page[size]"), parseIntDefault(c.Query("limit"), parseIntDefault(c.Query("size"), 20)))
	if pageSize < 1 {
		pageSize = 20
	}
	if pageSize > 100 {
		pageSize = 100
	}
	filter := c.Query("filter[search]")
	if filter == "" {
		filter = c.Query("search")
	}
	rows, total, listErr := svc.ListReactions(c.UserContext(), filter, c.Query("sort"), pageSize, (pageNumber-1)*pageSize)
	if listErr != nil {
		return writeMedicineErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{Status: "400", Title: "List failed", Detail: listErr.Error()}})
	}
	data := make([]dto.MotorReactionResource, 0, len(rows))
	for i := range rows {
		data = append(data, reactionResource(&rows[i]))
	}
	return response.WriteWithMeta(c, fiber.StatusOK, data, map[string]any{"total": total})
}

// ListMotorReactionsDatatable godoc
// @Summary List motor reactions (datatable)
// @Description Datatable response with simple pagination params.
// @Tags OPC - Motor Reaction
// @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.MotorReactionDataTableResponse
// @Failure 400 {object} dto.ErrorResponse
// @Failure 503 {object} dto.ErrorResponse
// @Router /api/v1/motor-reaction/get-all/dt [get]
func (h *MedicineHandler) ListReactionsDatatable(c *fiber.Ctx) error {
	svc, err := h.reactionSvc()
	if err != nil {
		return writeMedicineErrors(c, fiber.StatusServiceUnavailable, []jsonapi.ErrorObject{{Status: "503", Title: "Service unavailable", Detail: "an internal error occurred"}})
	}
	pageNumber := parseIntDefault(c.Query("page"), 1)
	if pageNumber < 1 {
		pageNumber = 1
	}
	size := parseIntDefault(c.Query("limit"), parseIntDefault(c.Query("size"), 20))
	if size < 1 {
		size = 20
	}
	if size > 100 {
		size = 100
	}
	rows, total, listErr := svc.ListReactions(c.UserContext(), c.Query("search"), "", size, (pageNumber-1)*size)
	if listErr != nil {
		return writeMedicineErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{Status: "400", Title: "List failed", Detail: listErr.Error()}})
	}
	data := make([]dto.MotorReactionResource, 0, len(rows))
	for i := range rows {
		data = append(data, reactionResource(&rows[i]))
	}
	return response.WriteWithMeta(c, fiber.StatusOK, data, map[string]any{"draw": parseIntDefault(c.Query("draw"), pageNumber), "records_total": total, "records_filtered": total})
}

func groupResource(row *medicine.MedicineGroup) dto.MedicineGroupResource {
	return dto.MedicineGroupResource{
		Type: "medicine_group",
		ID:   idString(row.ID),
		Attributes: dto.MedicineGroupAttributes{
			Name:      row.Name,
			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 reactionResource(row *medicine.MotorReaction) dto.MotorReactionResource {
	return dto.MotorReactionResource{
		Type: "motor_reaction",
		ID:   idString(row.ID),
		Attributes: dto.MotorReactionAttributes{
			Name:      row.Name,
			Score:     row.Score,
			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 writeMedicineErrors(c *fiber.Ctx, status int, errs []jsonapi.ErrorObject) error {
	return response.WriteErrors(c, status, apperrorsx.EnrichErrorObjects(status, errs))
}

func inferMedicineErrorCode(status int, title, detail string) (string, string) {
	lowerTitle := strings.ToLower(strings.TrimSpace(title))
	lowerDetail := strings.ToLower(strings.TrimSpace(detail))
	switch status {
	case fiber.StatusNotFound:
		if strings.Contains(lowerDetail, "group") || strings.Contains(lowerDetail, "reaction") {
			return apperrorsx.CodeDataNotFound, apperrorsx.ErrDataNotFound.ErrorCode
		}
		return apperrorsx.CodeMedicineNotFound, apperrorsx.ErrMedicineNotFound.ErrorCode
	case fiber.StatusConflict:
		return apperrorsx.CodeMedicineRelationDelete, apperrorsx.ErrMedicineRelationDelete.ErrorCode
	case fiber.StatusUnprocessableEntity:
		switch {
		case strings.Contains(lowerDetail, "uuid is invalid"):
			return apperrorsx.CodeMedicineInvalidUUID, apperrorsx.ErrMedicineInvalidUUID.ErrorCode
		case strings.Contains(lowerDetail, "id is required"):
			return apperrorsx.CodeMedicineIDRequired, apperrorsx.ErrMedicineIDRequired.ErrorCode
		case strings.Contains(lowerDetail, "id does not match"):
			return apperrorsx.CodeMedicineIDMismatch, apperrorsx.ErrMedicineIDMismatch.ErrorCode
		case strings.Contains(lowerDetail, "at least one attribute"):
			return apperrorsx.CodeMedicineAttributesRequired, apperrorsx.ErrMedicineAttributesRequired.ErrorCode
		case strings.Contains(lowerDetail, "name is required"), strings.Contains(lowerDetail, "name cannot be empty"):
			return apperrorsx.CodeMedicineNameRequired, apperrorsx.ErrMedicineNameRequired.ErrorCode
		case strings.Contains(lowerDetail, "medicine_group_id is invalid"):
			return apperrorsx.CodeMedicineGroupIDInvalid, apperrorsx.ErrMedicineGroupIDInvalid.ErrorCode
		case strings.Contains(lowerDetail, "motor_reaction_id is invalid"):
			return apperrorsx.CodeMedicineMotorReactionIDInvalid, apperrorsx.ErrMedicineMotorReactionIDInvalid.ErrorCode
		case strings.Contains(lowerDetail, "motor_reaction_ids"):
			return apperrorsx.CodeMedicineMotorReactionIDsInvalid, apperrorsx.ErrMedicineMotorReactionIDsInvalid.ErrorCode
		default:
			return apperrorsx.CodeMedicineInvalidPayload, apperrorsx.ErrMedicineInvalidPayload.ErrorCode
		}
	case fiber.StatusBadRequest:
		switch {
		case strings.Contains(lowerTitle, "invalid json"):
			return apperrorsx.CodeMedicineInvalidJSON, apperrorsx.ErrMedicineInvalidJSON.ErrorCode
		case strings.Contains(lowerTitle, "create failed"):
			return apperrorsx.CodeMedicineCreateFailed, apperrorsx.ErrMedicineCreateFailed.ErrorCode
		case strings.Contains(lowerTitle, "update failed"):
			return apperrorsx.CodeMedicineUpdateFailed, apperrorsx.ErrMedicineUpdateFailed.ErrorCode
		case strings.Contains(lowerTitle, "delete failed"):
			return apperrorsx.CodeMedicineDeleteFailed, apperrorsx.ErrMedicineDeleteFailed.ErrorCode
		case strings.Contains(lowerTitle, "list failed"):
			return apperrorsx.CodeMedicineListFailed, apperrorsx.ErrMedicineListFailed.ErrorCode
		default:
			return apperrorsx.CodeMedicineInvalidPayload, apperrorsx.ErrMedicineInvalidPayload.ErrorCode
		}
	case fiber.StatusServiceUnavailable:
		return apperrorsx.CodeBusinessRuleFailed, apperrorsx.ErrBusinessRuleFailed.ErrorCode
	default:
		return apperrorsx.CodeInternalServerError, apperrorsx.ErrInternal.ErrorCode
	}
}
