package handlers

import (
	"bytes"
	"context"
	"errors"
	"io"
	"net/http"
	"testing"
	"time"

	"github.com/gofiber/fiber/v2"

	"wucher/internal/domain/medicine"
	"wucher/internal/service"
	"wucher/internal/shared/pkg/uuidv7"
)

type memMedicineRepo struct {
	rows         map[string]*medicine.Medicine
	groupRows    map[string]*medicine.MedicineGroup
	reactionRows map[string]*medicine.MotorReaction

	createErr  error
	updateErr  error
	deleteErr  error
	getByIDErr error
	listErr    error

	listRows  []medicine.Medicine
	listTotal int64

	getByIDFn func(id []byte, call int) (*medicine.Medicine, error)
	getCalls  int

	lastCreate     *medicine.Medicine
	lastUpdate     *medicine.Medicine
	lastDeleteID   []byte
	lastDeleteBy   []byte
	lastListFilter string
	lastListSort   string
	lastListLimit  int
	lastListOffset int
}

func newMemMedicineRepo() *memMedicineRepo {
	return &memMedicineRepo{
		rows:         map[string]*medicine.Medicine{},
		groupRows:    map[string]*medicine.MedicineGroup{},
		reactionRows: map[string]*medicine.MotorReaction{},
	}
}

func (r *memMedicineRepo) Create(_ context.Context, row *medicine.Medicine) error {
	if r.createErr != nil {
		return r.createErr
	}
	if len(row.ID) == 0 {
		row.ID = uuidv7.MustBytes()
	}
	r.rows[string(row.ID)] = row
	r.lastCreate = row
	return nil
}

func (r *memMedicineRepo) Update(_ context.Context, row *medicine.Medicine) error {
	if r.updateErr != nil {
		return r.updateErr
	}
	r.rows[string(row.ID)] = row
	r.lastUpdate = row
	return nil
}

func (r *memMedicineRepo) Delete(_ context.Context, id []byte, deletedBy []byte) error {
	if r.deleteErr != nil {
		return r.deleteErr
	}
	r.lastDeleteID = append([]byte(nil), id...)
	r.lastDeleteBy = append([]byte(nil), deletedBy...)
	delete(r.rows, string(id))
	return nil
}

func (r *memMedicineRepo) GetByID(_ context.Context, id []byte) (*medicine.Medicine, error) {
	r.getCalls++
	if r.getByIDFn != nil {
		return r.getByIDFn(id, r.getCalls)
	}
	if r.getByIDErr != nil {
		return nil, r.getByIDErr
	}
	return r.rows[string(id)], nil
}

func (r *memMedicineRepo) List(_ context.Context, filter, sort string, limit, offset int) ([]medicine.Medicine, int64, error) {
	r.lastListFilter = filter
	r.lastListSort = sort
	r.lastListLimit = limit
	r.lastListOffset = offset
	if r.listErr != nil {
		return nil, 0, r.listErr
	}
	return r.listRows, r.listTotal, nil
}

func (r *memMedicineRepo) CreateGroup(_ context.Context, row *medicine.MedicineGroup) error {
	if len(row.ID) == 0 {
		row.ID = uuidv7.MustBytes()
	}
	r.groupRows[string(row.ID)] = row
	return nil
}

func (r *memMedicineRepo) UpdateGroup(_ context.Context, row *medicine.MedicineGroup) error {
	r.groupRows[string(row.ID)] = row
	return nil
}

func (r *memMedicineRepo) DeleteGroup(_ context.Context, id []byte, _ []byte) error {
	delete(r.groupRows, string(id))
	return nil
}

func (r *memMedicineRepo) GetGroupByID(_ context.Context, id []byte) (*medicine.MedicineGroup, error) {
	return r.groupRows[string(id)], nil
}

func (r *memMedicineRepo) ListGroups(_ context.Context, _ string, _ string, _ int, _ int) ([]medicine.MedicineGroup, int64, error) {
	out := make([]medicine.MedicineGroup, 0, len(r.groupRows))
	for _, v := range r.groupRows {
		out = append(out, *v)
	}
	return out, int64(len(out)), nil
}

func (r *memMedicineRepo) CreateReaction(_ context.Context, row *medicine.MotorReaction) error {
	if len(row.ID) == 0 {
		row.ID = uuidv7.MustBytes()
	}
	r.reactionRows[string(row.ID)] = row
	return nil
}

func (r *memMedicineRepo) UpdateReaction(_ context.Context, row *medicine.MotorReaction) error {
	r.reactionRows[string(row.ID)] = row
	return nil
}

func (r *memMedicineRepo) DeleteReaction(_ context.Context, id []byte, _ []byte) error {
	delete(r.reactionRows, string(id))
	return nil
}

func (r *memMedicineRepo) GetReactionByID(_ context.Context, id []byte) (*medicine.MotorReaction, error) {
	return r.reactionRows[string(id)], nil
}

func (r *memMedicineRepo) ListReactions(_ context.Context, _ string, _ string, _ int, _ int) ([]medicine.MotorReaction, int64, error) {
	out := make([]medicine.MotorReaction, 0, len(r.reactionRows))
	for _, v := range r.reactionRows {
		out = append(out, *v)
	}
	return out, int64(len(out)), nil
}

func newMedicineTestApp(h *MedicineHandler, actor []byte) *fiber.App {
	app := fiber.New()
	app.Use(func(c *fiber.Ctx) error {
		if len(actor) > 0 {
			c.Locals("user_id", actor)
		}
		return c.Next()
	})
	app.Post("/api/v1/medicine/create", h.Create)
	app.Patch("/api/v1/medicine/update/:uuid", h.Update)
	app.Delete("/api/v1/medicine/delete/:uuid", h.Delete)
	app.Get("/api/v1/medicine/get-all", h.List)
	app.Get("/api/v1/medicine/get-all/dt", h.ListDatatable)
	app.Post("/api/v1/medicine-group/create", h.CreateGroup)
	app.Patch("/api/v1/medicine-group/update/:uuid", h.UpdateGroup)
	app.Delete("/api/v1/medicine-group/delete/:uuid", h.DeleteGroup)
	app.Get("/api/v1/medicine-group/get-all", h.ListGroups)
	app.Get("/api/v1/medicine-group/get-all/dt", h.ListGroupsDatatable)
	app.Post("/api/v1/motor-reaction/create", h.CreateReaction)
	app.Patch("/api/v1/motor-reaction/update/:uuid", h.UpdateReaction)
	app.Delete("/api/v1/motor-reaction/delete/:uuid", h.DeleteReaction)
	app.Get("/api/v1/motor-reaction/get-all", h.ListReactions)
	app.Get("/api/v1/motor-reaction/get-all/dt", h.ListReactionsDatatable)
	return app
}

func doJSONRequestMedicine(t *testing.T, app *fiber.App, method, path string, body []byte) (*http.Response, []byte) {
	t.Helper()
	req, err := http.NewRequest(method, path, bytes.NewReader(body))
	if err != nil {
		t.Fatalf("new request: %v", err)
	}
	req.Header.Set("Content-Type", "application/json")
	resp, err := app.Test(req)
	if err != nil {
		t.Fatalf("app.Test: %v", err)
	}
	respBody, err := io.ReadAll(resp.Body)
	if err != nil {
		t.Fatalf("read body: %v", err)
	}
	return resp, respBody
}

func mustUUIDStringMedicine(t *testing.T, id []byte) string {
	t.Helper()
	s, err := uuidv7.BytesToString(id)
	if err != nil {
		t.Fatalf("uuid to string: %v", err)
	}
	return s
}

func mustParseUUIDMedicine(t *testing.T, raw string) []byte {
	t.Helper()
	id, err := uuidv7.ParseString(raw)
	if err != nil {
		t.Fatalf("parse uuid: %v", err)
	}
	return id
}

func TestNewMedicineHandler(t *testing.T) {
	h := NewMedicineHandler(service.NewMedicineService(newMemMedicineRepo()))
	if h == nil || h.validate == nil {
		t.Fatalf("expected handler and validator initialized")
	}
}

func TestMedicineHandlerCreate(t *testing.T) {
	t.Run("invalid json", func(t *testing.T) {
		repo := newMemMedicineRepo()
		h := NewMedicineHandler(service.NewMedicineService(repo))
		app := newMedicineTestApp(h, nil)

		resp, _ := doJSONRequestMedicine(t, app, http.MethodPost, "/api/v1/medicine/create", []byte(`{"data":`))
		if resp.StatusCode != http.StatusBadRequest {
			t.Fatalf("expected 400, got %d", resp.StatusCode)
		}
	})

	t.Run("validation error", func(t *testing.T) {
		repo := newMemMedicineRepo()
		h := NewMedicineHandler(service.NewMedicineService(repo))
		app := newMedicineTestApp(h, nil)

		resp, _ := doJSONRequestMedicine(t, app, http.MethodPost, "/api/v1/medicine/create", []byte(`{}`))
		if resp.StatusCode != http.StatusUnprocessableEntity {
			t.Fatalf("expected 422, got %d", resp.StatusCode)
		}
	})

	t.Run("name empty", func(t *testing.T) {
		repo := newMemMedicineRepo()
		h := NewMedicineHandler(service.NewMedicineService(repo))
		app := newMedicineTestApp(h, nil)

		body := []byte(`{"data":{"type":"medicine","attributes":{"name":"  ","pack":"500mg","column":2}}}`)
		resp, _ := doJSONRequestMedicine(t, app, http.MethodPost, "/api/v1/medicine/create", body)
		if resp.StatusCode != http.StatusUnprocessableEntity {
			t.Fatalf("expected 422, got %d", resp.StatusCode)
		}
	})

	t.Run("create error", func(t *testing.T) {
		repo := newMemMedicineRepo()
		repo.createErr = errors.New("create failed")
		h := NewMedicineHandler(service.NewMedicineService(repo))
		app := newMedicineTestApp(h, nil)

		body := []byte(`{"data":{"type":"medicine","attributes":{"name":"Paracetamol","pack":"500mg","column":2}}}`)
		resp, _ := doJSONRequestMedicine(t, app, http.MethodPost, "/api/v1/medicine/create", body)
		if resp.StatusCode != http.StatusBadRequest {
			t.Fatalf("expected 400, got %d", resp.StatusCode)
		}
	})

	t.Run("success with refetch", func(t *testing.T) {
		repo := newMemMedicineRepo()
		h := NewMedicineHandler(service.NewMedicineService(repo))
		actor := uuidv7.MustBytes()
		app := newMedicineTestApp(h, actor)

		body := []byte(`{"data":{"type":"medicine","attributes":{"name":"Paracetamol","note":"Main stock","pack":"500mg","unit":"tablet","column":2,"is_active":false}}}`)
		resp, _ := doJSONRequestMedicine(t, app, http.MethodPost, "/api/v1/medicine/create", body)
		if resp.StatusCode != http.StatusCreated {
			t.Fatalf("expected 201, got %d", resp.StatusCode)
		}
		if repo.lastCreate == nil || repo.lastCreate.Name != "Paracetamol" || repo.lastCreate.Note != "Main stock" || repo.lastCreate.Pack != "500mg" || repo.lastCreate.Unit != "tablet" || repo.lastCreate.Column != 2 {
			t.Fatalf("expected created row values")
		}
		if repo.lastCreate.IsActive {
			t.Fatalf("expected is_active false")
		}
		if string(repo.lastCreate.CreatedBy) != string(actor) || string(repo.lastCreate.UpdatedBy) != string(actor) {
			t.Fatalf("expected created_by and updated_by from actor")
		}
	})

	t.Run("success fallback and default column", func(t *testing.T) {
		repo := newMemMedicineRepo()
		repo.getByIDFn = func(_ []byte, call int) (*medicine.Medicine, error) {
			if call > 0 {
				return nil, errors.New("lookup failed")
			}
			return nil, nil
		}
		h := NewMedicineHandler(service.NewMedicineService(repo))
		app := newMedicineTestApp(h, nil)

		body := []byte(`{"data":{"type":"medicine","attributes":{"name":"Ibuprofen","pack":"200mg"}}}`)
		resp, _ := doJSONRequestMedicine(t, app, http.MethodPost, "/api/v1/medicine/create", body)
		if resp.StatusCode != http.StatusCreated {
			t.Fatalf("expected 201, got %d", resp.StatusCode)
		}
		if repo.lastCreate == nil || repo.lastCreate.Column != 0 {
			t.Fatalf("expected default column 0")
		}
	})

	t.Run("success without sortkey", func(t *testing.T) {
		repo := newMemMedicineRepo()
		h := NewMedicineHandler(service.NewMedicineService(repo))
		app := newMedicineTestApp(h, nil)

		body := []byte(`{"data":{"type":"medicine","attributes":{"name":"Ibuprofen","pack":"200mg","column":1}}}`)
		resp, _ := doJSONRequestMedicine(t, app, http.MethodPost, "/api/v1/medicine/create", body)
		if resp.StatusCode != http.StatusCreated {
			t.Fatalf("expected 201, got %d", resp.StatusCode)
		}
		if repo.lastCreate == nil {
			t.Fatalf("expected create called")
		}
	})
}

func TestMedicineHandlerUpdate(t *testing.T) {
	t.Run("invalid uuid", func(t *testing.T) {
		repo := newMemMedicineRepo()
		h := NewMedicineHandler(service.NewMedicineService(repo))
		app := newMedicineTestApp(h, nil)

		resp, _ := doJSONRequestMedicine(t, app, http.MethodPatch, "/api/v1/medicine/update/not-uuid", []byte(`{}`))
		if resp.StatusCode != http.StatusUnprocessableEntity {
			t.Fatalf("expected 422, got %d", resp.StatusCode)
		}
	})

	t.Run("invalid json", func(t *testing.T) {
		repo := newMemMedicineRepo()
		h := NewMedicineHandler(service.NewMedicineService(repo))
		app := newMedicineTestApp(h, nil)
		id := mustUUIDStringMedicine(t, uuidv7.MustBytes())

		resp, _ := doJSONRequestMedicine(t, app, http.MethodPatch, "/api/v1/medicine/update/"+id, []byte(`{"data":`))
		if resp.StatusCode != http.StatusBadRequest {
			t.Fatalf("expected 400, got %d", resp.StatusCode)
		}
	})

	t.Run("validation error", func(t *testing.T) {
		repo := newMemMedicineRepo()
		h := NewMedicineHandler(service.NewMedicineService(repo))
		app := newMedicineTestApp(h, nil)
		id := mustUUIDStringMedicine(t, uuidv7.MustBytes())

		resp, _ := doJSONRequestMedicine(t, app, http.MethodPatch, "/api/v1/medicine/update/"+id, []byte(`{"data":{"type":"x","id":"`+id+`","attributes":{"name":"A"}}}`))
		if resp.StatusCode != http.StatusUnprocessableEntity {
			t.Fatalf("expected 422, got %d", resp.StatusCode)
		}
	})

	t.Run("id required", func(t *testing.T) {
		repo := newMemMedicineRepo()
		h := NewMedicineHandler(service.NewMedicineService(repo))
		app := newMedicineTestApp(h, nil)
		id := mustUUIDStringMedicine(t, uuidv7.MustBytes())

		resp, _ := doJSONRequestMedicine(t, app, http.MethodPatch, "/api/v1/medicine/update/"+id, []byte(`{"data":{"type":"medicine","id":"","attributes":{"name":"A"}}}`))
		if resp.StatusCode != http.StatusUnprocessableEntity {
			t.Fatalf("expected 422, got %d", resp.StatusCode)
		}
	})

	t.Run("id mismatch", func(t *testing.T) {
		repo := newMemMedicineRepo()
		h := NewMedicineHandler(service.NewMedicineService(repo))
		app := newMedicineTestApp(h, nil)
		id := mustUUIDStringMedicine(t, uuidv7.MustBytes())
		other := mustUUIDStringMedicine(t, uuidv7.MustBytes())

		resp, _ := doJSONRequestMedicine(t, app, http.MethodPatch, "/api/v1/medicine/update/"+id, []byte(`{"data":{"type":"medicine","id":"`+other+`","attributes":{"name":"A"}}}`))
		if resp.StatusCode != http.StatusUnprocessableEntity {
			t.Fatalf("expected 422, got %d", resp.StatusCode)
		}
	})

	t.Run("no attributes", func(t *testing.T) {
		repo := newMemMedicineRepo()
		h := NewMedicineHandler(service.NewMedicineService(repo))
		app := newMedicineTestApp(h, nil)
		id := mustUUIDStringMedicine(t, uuidv7.MustBytes())

		resp, _ := doJSONRequestMedicine(t, app, http.MethodPatch, "/api/v1/medicine/update/"+id, []byte(`{"data":{"type":"medicine","id":"`+id+`","attributes":{}}}`))
		if resp.StatusCode != http.StatusUnprocessableEntity {
			t.Fatalf("expected 422, got %d", resp.StatusCode)
		}
	})

	t.Run("not found", func(t *testing.T) {
		repo := newMemMedicineRepo()
		h := NewMedicineHandler(service.NewMedicineService(repo))
		app := newMedicineTestApp(h, nil)
		id := mustUUIDStringMedicine(t, uuidv7.MustBytes())

		resp, _ := doJSONRequestMedicine(t, app, http.MethodPatch, "/api/v1/medicine/update/"+id, []byte(`{"data":{"type":"medicine","id":"`+id+`","attributes":{"name":"A"}}}`))
		if resp.StatusCode != http.StatusNotFound {
			t.Fatalf("expected 404, got %d", resp.StatusCode)
		}
	})

	t.Run("name empty", func(t *testing.T) {
		repo := newMemMedicineRepo()
		id := uuidv7.MustBytes()
		repo.rows[string(id)] = &medicine.Medicine{ID: id, Name: "Old", Pack:"100mg", Column: 1}
		h := NewMedicineHandler(service.NewMedicineService(repo))
		app := newMedicineTestApp(h, nil)
		idStr := mustUUIDStringMedicine(t, id)

		resp, _ := doJSONRequestMedicine(t, app, http.MethodPatch, "/api/v1/medicine/update/"+idStr, []byte(`{"data":{"type":"medicine","id":"`+idStr+`","attributes":{"name":"  "}}}`))
		if resp.StatusCode != http.StatusUnprocessableEntity {
			t.Fatalf("expected 422, got %d", resp.StatusCode)
		}
	})

	t.Run("update error", func(t *testing.T) {
		repo := newMemMedicineRepo()
		id := uuidv7.MustBytes()
		repo.rows[string(id)] = &medicine.Medicine{ID: id, Name: "Old", Pack:"100mg", Column: 1}
		repo.updateErr = errors.New("update failed")
		h := NewMedicineHandler(service.NewMedicineService(repo))
		app := newMedicineTestApp(h, nil)
		idStr := mustUUIDStringMedicine(t, id)

		resp, _ := doJSONRequestMedicine(t, app, http.MethodPatch, "/api/v1/medicine/update/"+idStr, []byte(`{"data":{"type":"medicine","id":"`+idStr+`","attributes":{"name":"New"}}}`))
		if resp.StatusCode != http.StatusBadRequest {
			t.Fatalf("expected 400, got %d", resp.StatusCode)
		}
	})

	t.Run("success with refetch", func(t *testing.T) {
		repo := newMemMedicineRepo()
		id := uuidv7.MustBytes()
		repo.rows[string(id)] = &medicine.Medicine{ID: id, Name: "Old", Pack: "100mg", Column: 1}
		h := NewMedicineHandler(service.NewMedicineService(repo))
		actor := uuidv7.MustBytes()
		app := newMedicineTestApp(h, actor)
		idStr := mustUUIDStringMedicine(t, id)

		resp, _ := doJSONRequestMedicine(t, app, http.MethodPatch, "/api/v1/medicine/update/"+idStr, []byte(`{"data":{"type":"medicine","id":"`+idStr+`","attributes":{"name":"New","pack":"250mg","column":3}}}`))
		if resp.StatusCode != http.StatusOK {
			t.Fatalf("expected 200, got %d", resp.StatusCode)
		}
		if repo.lastUpdate == nil || repo.lastUpdate.Name != "New" || repo.lastUpdate.Pack != "250mg" || repo.lastUpdate.Column != 3 {
			t.Fatalf("expected updated values")
		}
		if string(repo.lastUpdate.UpdatedBy) != string(actor) {
			t.Fatalf("expected updated_by from actor")
		}
	})

	t.Run("success update note and is_active", func(t *testing.T) {
		repo := newMemMedicineRepo()
		id := uuidv7.MustBytes()
		repo.rows[string(id)] = &medicine.Medicine{ID: id, Name: "Old", Pack: "100mg", Column: 1, Note: "Old", IsActive: true}
		h := NewMedicineHandler(service.NewMedicineService(repo))
		app := newMedicineTestApp(h, nil)
		idStr := mustUUIDStringMedicine(t, id)

		resp, _ := doJSONRequestMedicine(t, app, http.MethodPatch, "/api/v1/medicine/update/"+idStr, []byte(`{"data":{"type":"medicine","id":"`+idStr+`","attributes":{"note":"Updated note","unit":"inhalation","is_active":false}}}`))
		if resp.StatusCode != http.StatusOK {
			t.Fatalf("expected 200, got %d", resp.StatusCode)
		}
		if repo.lastUpdate == nil {
			t.Fatalf("expected update called")
		}
		if repo.lastUpdate.Note != "Updated note" {
			t.Fatalf("expected note updated")
		}
		if repo.lastUpdate.Unit != "inhalation" {
			t.Fatalf("expected unit updated")
		}
		if repo.lastUpdate.IsActive {
			t.Fatalf("expected is_active false")
		}
	})

	t.Run("success update is_active only", func(t *testing.T) {
		repo := newMemMedicineRepo()
		id := uuidv7.MustBytes()
		repo.rows[string(id)] = &medicine.Medicine{ID: id, Name: "Old", Pack:"100mg", Column: 1}
		h := NewMedicineHandler(service.NewMedicineService(repo))
		app := newMedicineTestApp(h, nil)
		idStr := mustUUIDStringMedicine(t, id)

		resp, _ := doJSONRequestMedicine(t, app, http.MethodPatch, "/api/v1/medicine/update/"+idStr, []byte(`{"data":{"type":"medicine","id":"`+idStr+`","attributes":{"is_active":false}}}`))
		if resp.StatusCode != http.StatusOK {
			t.Fatalf("expected 200, got %d", resp.StatusCode)
		}
		if repo.lastUpdate == nil {
			t.Fatalf("expected update called")
		}
	})

	t.Run("accept empty motor_reaction_id as clear value", func(t *testing.T) {
		repo := newMemMedicineRepo()
		id := uuidv7.MustBytes()
		reactionID := uuidv7.MustBytes()
		repo.rows[string(id)] = &medicine.Medicine{
			ID:              id,
			Name:            "Old",
			Pack:           "100mg",
			Column:          1,
			MotorReactionID: append([]byte(nil), reactionID...),
		}
		h := NewMedicineHandler(service.NewMedicineService(repo))
		app := newMedicineTestApp(h, nil)
		idStr := mustUUIDStringMedicine(t, id)

		resp, _ := doJSONRequestMedicine(t, app, http.MethodPatch, "/api/v1/medicine/update/"+idStr, []byte(`{"data":{"type":"medicine","id":"`+idStr+`","attributes":{"motor_reaction_id":""}}}`))
		if resp.StatusCode != http.StatusOK {
			t.Fatalf("expected 200, got %d", resp.StatusCode)
		}
		if repo.lastUpdate == nil {
			t.Fatalf("expected update called")
		}
		if repo.lastUpdate.MotorReactionID != nil {
			t.Fatalf("expected motor_reaction_id cleared on empty string")
		}
	})

	t.Run("success update medicine_group_id", func(t *testing.T) {
		repo := newMemMedicineRepo()
		id := uuidv7.MustBytes()
		oldGroupID := uuidv7.MustBytes()
		newGroupID := uuidv7.MustBytes()
		repo.rows[string(id)] = &medicine.Medicine{
			ID:              id,
			Name:            "Old",
			Pack:           "100mg",
			Column:          1,
			MedicineGroupID: append([]byte(nil), oldGroupID...),
			MedicineGroup:   &medicine.MedicineGroup{ID: append([]byte(nil), oldGroupID...), Name: "Old Group"},
		}
		h := NewMedicineHandler(service.NewMedicineService(repo))
		app := newMedicineTestApp(h, nil)
		idStr := mustUUIDStringMedicine(t, id)
		newGroupIDStr := mustUUIDStringMedicine(t, newGroupID)

		resp, _ := doJSONRequestMedicine(t, app, http.MethodPatch, "/api/v1/medicine/update/"+idStr, []byte(`{"data":{"type":"medicine","id":"`+idStr+`","attributes":{"medicine_group_id":"`+newGroupIDStr+`"}}}`))
		if resp.StatusCode != http.StatusOK {
			t.Fatalf("expected 200, got %d", resp.StatusCode)
		}
		if repo.lastUpdate == nil {
			t.Fatalf("expected update called")
		}
		if string(repo.lastUpdate.MedicineGroupID) != string(newGroupID) {
			t.Fatalf("expected medicine_group_id updated")
		}
		if repo.lastUpdate.MedicineGroup != nil {
			t.Fatalf("expected medicine_group association reset on FK update")
		}
	})

	t.Run("success fallback when refetch fails", func(t *testing.T) {
		repo := newMemMedicineRepo()
		id := uuidv7.MustBytes()
		existing := &medicine.Medicine{ID: id, Name: "Old", Pack:"100mg", Column: 1}
		repo.getByIDFn = func(_ []byte, call int) (*medicine.Medicine, error) {
			if call == 1 {
				return existing, nil
			}
			return nil, errors.New("second lookup failed")
		}
		h := NewMedicineHandler(service.NewMedicineService(repo))
		app := newMedicineTestApp(h, nil)
		idStr := mustUUIDStringMedicine(t, id)

		resp, _ := doJSONRequestMedicine(t, app, http.MethodPatch, "/api/v1/medicine/update/"+idStr, []byte(`{"data":{"type":"medicine","id":"`+idStr+`","attributes":{"pack":"Only pack"}}}`))
		if resp.StatusCode != http.StatusOK {
			t.Fatalf("expected 200, got %d", resp.StatusCode)
		}
	})
}

func TestMedicineHandlerDelete(t *testing.T) {
	t.Run("invalid uuid", func(t *testing.T) {
		repo := newMemMedicineRepo()
		h := NewMedicineHandler(service.NewMedicineService(repo))
		app := newMedicineTestApp(h, nil)

		resp, _ := doJSONRequestMedicine(t, app, http.MethodDelete, "/api/v1/medicine/delete/not-uuid", nil)
		if resp.StatusCode != http.StatusUnprocessableEntity {
			t.Fatalf("expected 422, got %d", resp.StatusCode)
		}
	})

	t.Run("delete error", func(t *testing.T) {
		repo := newMemMedicineRepo()
		repo.deleteErr = errors.New("delete failed")
		h := NewMedicineHandler(service.NewMedicineService(repo))
		app := newMedicineTestApp(h, nil)
		id := mustUUIDStringMedicine(t, uuidv7.MustBytes())

		resp, _ := doJSONRequestMedicine(t, app, http.MethodDelete, "/api/v1/medicine/delete/"+id, nil)
		if resp.StatusCode != http.StatusBadRequest {
			t.Fatalf("expected 400, got %d", resp.StatusCode)
		}
	})

	t.Run("success", func(t *testing.T) {
		repo := newMemMedicineRepo()
		h := NewMedicineHandler(service.NewMedicineService(repo))
		actor := uuidv7.MustBytes()
		app := newMedicineTestApp(h, actor)
		id := uuidv7.MustBytes()
		idStr := mustUUIDStringMedicine(t, id)

		resp, _ := doJSONRequestMedicine(t, app, http.MethodDelete, "/api/v1/medicine/delete/"+idStr, nil)
		if resp.StatusCode != http.StatusOK {
			t.Fatalf("expected 200, got %d", resp.StatusCode)
		}
		if string(repo.lastDeleteBy) != string(actor) {
			t.Fatalf("expected deleted_by from actor")
		}
	})
}

func TestMedicineHandlerList(t *testing.T) {
	t.Run("list error", func(t *testing.T) {
		repo := newMemMedicineRepo()
		repo.listErr = errors.New("list failed")
		h := NewMedicineHandler(service.NewMedicineService(repo))
		app := newMedicineTestApp(h, nil)

		resp, _ := doJSONRequestMedicine(t, app, http.MethodGet, "/api/v1/medicine/get-all", nil)
		if resp.StatusCode != http.StatusBadRequest {
			t.Fatalf("expected 400, got %d", resp.StatusCode)
		}
	})

	t.Run("success with filter name fallback and clamp max", func(t *testing.T) {
		repo := newMemMedicineRepo()
		repo.listRows = []medicine.Medicine{{ID: uuidv7.MustBytes(), Name: "Paracetamol", Note: "Main stock", Pack:"500mg", Column: 2, IsActive: true, CreatedAt: time.Now(), UpdatedAt: time.Now()}}
		repo.listTotal = 1
		h := NewMedicineHandler(service.NewMedicineService(repo))
		app := newMedicineTestApp(h, nil)

		resp, _ := doJSONRequestMedicine(t, app, http.MethodGet, "/api/v1/medicine/get-all?filter[name]=abc&page[number]=0&page=0&page[size]=0&limit=101&sort=-name", nil)
		if resp.StatusCode != http.StatusOK {
			t.Fatalf("expected 200, got %d", resp.StatusCode)
		}
		if repo.lastListFilter != "abc" || repo.lastListSort != "name DESC" || repo.lastListLimit != 0 || repo.lastListOffset != 0 {
			t.Fatalf("unexpected list params: filter=%q sort=%q limit=%d offset=%d", repo.lastListFilter, repo.lastListSort, repo.lastListLimit, repo.lastListOffset)
		}
	})

	t.Run("success with search and clamp min", func(t *testing.T) {
		repo := newMemMedicineRepo()
		repo.listRows = []medicine.Medicine{}
		repo.listTotal = 0
		h := NewMedicineHandler(service.NewMedicineService(repo))
		app := newMedicineTestApp(h, nil)

		resp, _ := doJSONRequestMedicine(t, app, http.MethodGet, "/api/v1/medicine/get-all?page=2&size=-1&search=needle", nil)
		if resp.StatusCode != http.StatusOK {
			t.Fatalf("expected 200, got %d", resp.StatusCode)
		}
		if repo.lastListFilter != "needle" || repo.lastListLimit != 0 || repo.lastListOffset != 0 {
			t.Fatalf("unexpected list params: filter=%q limit=%d offset=%d", repo.lastListFilter, repo.lastListLimit, repo.lastListOffset)
		}
	})
}

func TestMedicineHandlerListDatatable(t *testing.T) {
	t.Run("list error", func(t *testing.T) {
		repo := newMemMedicineRepo()
		repo.listErr = errors.New("list failed")
		h := NewMedicineHandler(service.NewMedicineService(repo))
		app := newMedicineTestApp(h, nil)

		resp, _ := doJSONRequestMedicine(t, app, http.MethodGet, "/api/v1/medicine/get-all/dt", nil)
		if resp.StatusCode != http.StatusBadRequest {
			t.Fatalf("expected 400, got %d", resp.StatusCode)
		}
	})

	t.Run("success clamp max and page floor", func(t *testing.T) {
		repo := newMemMedicineRepo()
		repo.listRows = []medicine.Medicine{{ID: uuidv7.MustBytes(), Name: "Paracetamol", Pack:"500mg", Column: 2, CreatedAt: time.Now(), UpdatedAt: time.Now()}}
		repo.listTotal = 1
		h := NewMedicineHandler(service.NewMedicineService(repo))
		app := newMedicineTestApp(h, nil)

		resp, _ := doJSONRequestMedicine(t, app, http.MethodGet, "/api/v1/medicine/get-all/dt?page=0&limit=0&size=101&draw=7&search=abc", nil)
		if resp.StatusCode != http.StatusOK {
			t.Fatalf("expected 200, got %d", resp.StatusCode)
		}
		if repo.lastListFilter != "abc" || repo.lastListLimit != 100 || repo.lastListOffset != 0 {
			t.Fatalf("unexpected list params: filter=%q limit=%d offset=%d", repo.lastListFilter, repo.lastListLimit, repo.lastListOffset)
		}
	})

	t.Run("success clamp min", func(t *testing.T) {
		repo := newMemMedicineRepo()
		repo.listRows = []medicine.Medicine{}
		repo.listTotal = 0
		h := NewMedicineHandler(service.NewMedicineService(repo))
		app := newMedicineTestApp(h, nil)

		resp, _ := doJSONRequestMedicine(t, app, http.MethodGet, "/api/v1/medicine/get-all/dt?page=2&limit=0&size=-1", nil)
		if resp.StatusCode != http.StatusOK {
			t.Fatalf("expected 200, got %d", resp.StatusCode)
		}
		if repo.lastListLimit != 20 || repo.lastListOffset != 20 {
			t.Fatalf("unexpected list params: limit=%d offset=%d", repo.lastListLimit, repo.lastListOffset)
		}
	})
}

func TestMedicineHandler_GroupAndReactionEndpoints(t *testing.T) {
	repo := newMemMedicineRepo()
	h := NewMedicineHandler(service.NewMedicineService(repo))
	app := newMedicineTestApp(h, uuidv7.MustBytes())

	groupCreate := []byte(`{"data":{"type":"medicine_group_create","attributes":{"name":"Spritze","is_active":true}}}`)
	resp, body := doJSONRequestMedicine(t, app, http.MethodPost, "/api/v1/medicine-group/create", groupCreate)
	if resp.StatusCode != http.StatusCreated {
		t.Fatalf("expected 201 group create, got %d body=%s", resp.StatusCode, string(body))
	}
	var groupID string
	for _, g := range repo.groupRows {
		groupID = mustUUIDStringMedicine(t, g.ID)
		break
	}
	if groupID == "" {
		t.Fatalf("expected group id")
	}
	resp, _ = doJSONRequestMedicine(t, app, http.MethodGet, "/api/v1/medicine-group/get-all", nil)
	if resp.StatusCode != http.StatusOK {
		t.Fatalf("expected 200 group list, got %d", resp.StatusCode)
	}
	resp, _ = doJSONRequestMedicine(t, app, http.MethodGet, "/api/v1/medicine-group/get-all/dt", nil)
	if resp.StatusCode != http.StatusOK {
		t.Fatalf("expected 200 group datatable, got %d", resp.StatusCode)
	}
	groupUpdate := []byte(`{"data":{"type":"medicine_group_update","id":"` + groupID + `","attributes":{"name":"Monitoring"}}}`)
	resp, _ = doJSONRequestMedicine(t, app, http.MethodPatch, "/api/v1/medicine-group/update/"+groupID, groupUpdate)
	if resp.StatusCode != http.StatusOK {
		t.Fatalf("expected 200 group update, got %d", resp.StatusCode)
	}
	resp, _ = doJSONRequestMedicine(t, app, http.MethodDelete, "/api/v1/medicine-group/delete/"+groupID, nil)
	if resp.StatusCode != http.StatusOK {
		t.Fatalf("expected 200 group delete, got %d", resp.StatusCode)
	}

	reactionCreate := []byte(`{"data":{"type":"motor_reaction_create","attributes":{"name":"gezielt auf Schmerzreiz","score":5,"is_active":true}}}`)
	resp, body = doJSONRequestMedicine(t, app, http.MethodPost, "/api/v1/motor-reaction/create", reactionCreate)
	if resp.StatusCode != http.StatusCreated {
		t.Fatalf("expected 201 reaction create, got %d body=%s", resp.StatusCode, string(body))
	}
	var reactionID string
	for _, r := range repo.reactionRows {
		reactionID = mustUUIDStringMedicine(t, r.ID)
		break
	}
	if reactionID == "" {
		t.Fatalf("expected reaction id")
	}
	if stored := repo.reactionRows[string(mustParseUUIDMedicine(t, reactionID))]; stored == nil || stored.Score == nil || *stored.Score != 5 {
		t.Fatalf("expected created reaction score=5")
	}
	resp, _ = doJSONRequestMedicine(t, app, http.MethodGet, "/api/v1/motor-reaction/get-all", nil)
	if resp.StatusCode != http.StatusOK {
		t.Fatalf("expected 200 reaction list, got %d", resp.StatusCode)
	}
	resp, _ = doJSONRequestMedicine(t, app, http.MethodGet, "/api/v1/motor-reaction/get-all/dt", nil)
	if resp.StatusCode != http.StatusOK {
		t.Fatalf("expected 200 reaction datatable, got %d", resp.StatusCode)
	}
	reactionUpdate := []byte(`{"data":{"type":"motor_reaction_update","id":"` + reactionID + `","attributes":{"name":"keine Reaktion","score":1}}}`)
	resp, _ = doJSONRequestMedicine(t, app, http.MethodPatch, "/api/v1/motor-reaction/update/"+reactionID, reactionUpdate)
	if resp.StatusCode != http.StatusOK {
		t.Fatalf("expected 200 reaction update, got %d", resp.StatusCode)
	}
	if stored := repo.reactionRows[string(mustParseUUIDMedicine(t, reactionID))]; stored == nil || stored.Score == nil || *stored.Score != 1 {
		t.Fatalf("expected updated reaction score=1")
	}
	resp, _ = doJSONRequestMedicine(t, app, http.MethodDelete, "/api/v1/motor-reaction/delete/"+reactionID, nil)
	if resp.StatusCode != http.StatusOK {
		t.Fatalf("expected 200 reaction delete, got %d", resp.StatusCode)
	}
}

func TestMedicineHandler_MotorReactionScoreNullable(t *testing.T) {
	repo := newMemMedicineRepo()
	svc := service.NewMedicineService(repo)
	h := NewMedicineHandler(svc)
	app := newMedicineTestApp(h, uuidv7.MustBytes())

	t.Run("create score null", func(t *testing.T) {
		resp, body := doJSONRequestMedicine(t, app, http.MethodPost, "/api/v1/motor-reaction/create", []byte(`{"data":{"type":"motor_reaction_create","attributes":{"name":"no score","score":null}}}`))
		if resp.StatusCode != http.StatusCreated {
			t.Fatalf("expected 201, got %d body=%s", resp.StatusCode, string(body))
		}
		for _, row := range repo.reactionRows {
			if row.Name == "no score" {
				if row.Score != nil {
					t.Fatalf("expected score nil when payload score=null")
				}
				return
			}
		}
		t.Fatalf("created reaction not found")
	})

	t.Run("create score zero", func(t *testing.T) {
		resp, body := doJSONRequestMedicine(t, app, http.MethodPost, "/api/v1/motor-reaction/create", []byte(`{"data":{"type":"motor_reaction_create","attributes":{"name":"zero score","score":0}}}`))
		if resp.StatusCode != http.StatusCreated {
			t.Fatalf("expected 201, got %d body=%s", resp.StatusCode, string(body))
		}
		for _, row := range repo.reactionRows {
			if row.Name == "zero score" {
				if row.Score == nil || *row.Score != 0 {
					t.Fatalf("expected score pointer with value 0")
				}
				return
			}
		}
		t.Fatalf("created reaction not found")
	})
}

func TestMedicineResource(t *testing.T) {
	id := uuidv7.MustBytes()
	createdBy := uuidv7.MustBytes()
	updatedBy := uuidv7.MustBytes()
	deletedBy := uuidv7.MustBytes()
	now := time.Now().UTC().Truncate(time.Second)
	deletedAt := now.Add(time.Hour)

	row := &medicine.Medicine{
		ID:        id,
		Name:      "Paracetamol",
		Note:      "Main stock",
		Pack:      "500mg",
		Unit:      "tablet",
		Column:    2,
		IsActive:  true,
		CreatedAt: now,
		CreatedBy: createdBy,
		UpdatedAt: now,
		UpdatedBy: updatedBy,
		DeletedAt: &deletedAt,
		DeletedBy: deletedBy,
	}

	res := medicineResource(row)
	if res.Type != "medicine" {
		t.Fatalf("unexpected type: %s", res.Type)
	}
	if res.Attributes.Note != "Main stock" || res.Attributes.Unit != "tablet" || !res.Attributes.IsActive {
		t.Fatalf("expected note and is_active in resource")
	}
	if res.ID == "" || res.Attributes.CreatedBy == "" || res.Attributes.UpdatedBy == "" || res.Attributes.DeletedBy == "" {
		t.Fatalf("expected UUID fields in resource")
	}
	if res.Attributes.Column != 2 {
		t.Fatalf("expected column in resource")
	}
	if res.Attributes.CreatedAt == "" || res.Attributes.UpdatedAt == "" || res.Attributes.DeletedAt == "" {
		t.Fatalf("expected time fields in resource")
	}
}

func TestIntOrDefault64(t *testing.T) {
	if got := intOrDefault64(nil, 99); got != 99 {
		t.Fatalf("expected default for nil pointer")
	}
	v := int64(7)
	if got := intOrDefault64(&v, 99); got != 7 {
		t.Fatalf("expected pointer value when not nil")
	}
}
