package handlers

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

	"github.com/gofiber/fiber/v2"

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

type memForcesPresentRepo struct {
	rows map[string]*forces_present.ForcesPresent

	createErr  error
	updateErr  error
	deleteErr  error
	getByIDErr error
	listErr    error

	listRows  []forces_present.ForcesPresent
	listTotal int64

	getByIDFn func(id []byte, call int) (*forces_present.ForcesPresent, error)
	getCalls  int

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

func newMemForcesPresentRepo() *memForcesPresentRepo {
	return &memForcesPresentRepo{rows: map[string]*forces_present.ForcesPresent{}}
}

func (r *memForcesPresentRepo) Create(_ context.Context, row *forces_present.ForcesPresent) 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 *memForcesPresentRepo) Update(_ context.Context, row *forces_present.ForcesPresent) error {
	if r.updateErr != nil {
		return r.updateErr
	}
	r.rows[string(row.ID)] = row
	r.lastUpdate = row
	return nil
}

func (r *memForcesPresentRepo) 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 *memForcesPresentRepo) GetByID(_ context.Context, id []byte) (*forces_present.ForcesPresent, 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 *memForcesPresentRepo) List(_ context.Context, filter, sort string, limit, offset int) ([]forces_present.ForcesPresent, 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 newForcesPresentTestApp(h *ForcesPresentHandler, 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/forces-present/create", h.Create)
	app.Patch("/api/v1/forces-present/update/:uuid", h.Update)
	app.Delete("/api/v1/forces-present/delete/:uuid", h.Delete)
	app.Get("/api/v1/forces-present/get-all", h.List)
	app.Get("/api/v1/forces-present/get-all/dt", h.ListDatatable)
	return app
}

func doJSONRequestForcesPresent(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 mustUUIDStringForcesPresent(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 TestNewForcesPresentHandler(t *testing.T) {
	h := NewForcesPresentHandler(service.NewForcesPresentService(newMemForcesPresentRepo()))
	if h == nil || h.validate == nil {
		t.Fatalf("expected handler and validator initialized")
	}
}

func TestForcesPresentHandlerCreate(t *testing.T) {
	t.Run("invalid json", func(t *testing.T) {
		repo := newMemForcesPresentRepo()
		h := NewForcesPresentHandler(service.NewForcesPresentService(repo))
		app := newForcesPresentTestApp(h, nil)

		resp, _ := doJSONRequestForcesPresent(t, app, http.MethodPost, "/api/v1/forces-present/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 := newMemForcesPresentRepo()
		h := NewForcesPresentHandler(service.NewForcesPresentService(repo))
		app := newForcesPresentTestApp(h, nil)

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

	t.Run("name empty", func(t *testing.T) {
		repo := newMemForcesPresentRepo()
		h := NewForcesPresentHandler(service.NewForcesPresentService(repo))
		app := newForcesPresentTestApp(h, nil)

		body := []byte(`{"data":{"type":"forces_present","attributes":{"name":"  "}}}`)
		resp, _ := doJSONRequestForcesPresent(t, app, http.MethodPost, "/api/v1/forces-present/create", body)
		if resp.StatusCode != http.StatusUnprocessableEntity {
			t.Fatalf("expected 422, got %d", resp.StatusCode)
		}
	})

	t.Run("create error", func(t *testing.T) {
		repo := newMemForcesPresentRepo()
		repo.createErr = errors.New("create failed")
		h := NewForcesPresentHandler(service.NewForcesPresentService(repo))
		app := newForcesPresentTestApp(h, nil)

		body := []byte(`{"data":{"type":"forces_present","attributes":{"name":"Team A"}}}`)
		resp, _ := doJSONRequestForcesPresent(t, app, http.MethodPost, "/api/v1/forces-present/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 := newMemForcesPresentRepo()
		h := NewForcesPresentHandler(service.NewForcesPresentService(repo))
		actor := uuidv7.MustBytes()
		app := newForcesPresentTestApp(h, actor)

		body := []byte(`{"data":{"type":"forces_present","attributes":{"name":"Team A","sortkey":3,"note":"On-site","is_active":false}}}`)
		resp, _ := doJSONRequestForcesPresent(t, app, http.MethodPost, "/api/v1/forces-present/create", body)
		if resp.StatusCode != http.StatusCreated {
			t.Fatalf("expected 201, got %d", resp.StatusCode)
		}
		if repo.lastCreate == nil {
			t.Fatalf("expected row created")
		}
		if repo.lastCreate.Name != "Team A" || repo.lastCreate.Note != "On-site" {
			t.Fatalf("expected created values")
		}
		if repo.lastCreate.SortKey == nil || *repo.lastCreate.SortKey != 3 {
			t.Fatalf("expected sortkey value")
		}
		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 when refetch error", func(t *testing.T) {
		repo := newMemForcesPresentRepo()
		repo.getByIDFn = func(_ []byte, call int) (*forces_present.ForcesPresent, error) {
			if call > 0 {
				return nil, errors.New("lookup failed")
			}
			return nil, nil
		}
		h := NewForcesPresentHandler(service.NewForcesPresentService(repo))
		app := newForcesPresentTestApp(h, nil)

		body := []byte(`{"data":{"type":"forces_present","attributes":{"name":"Team B"}}}`)
		resp, _ := doJSONRequestForcesPresent(t, app, http.MethodPost, "/api/v1/forces-present/create", body)
		if resp.StatusCode != http.StatusCreated {
			t.Fatalf("expected 201, got %d", resp.StatusCode)
		}
		if repo.lastCreate == nil {
			t.Fatalf("expected fallback create with empty description")
		}
	})
}

func TestForcesPresentHandlerUpdate(t *testing.T) {
	t.Run("invalid uuid", func(t *testing.T) {
		repo := newMemForcesPresentRepo()
		h := NewForcesPresentHandler(service.NewForcesPresentService(repo))
		app := newForcesPresentTestApp(h, nil)

		resp, _ := doJSONRequestForcesPresent(t, app, http.MethodPatch, "/api/v1/forces-present/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 := newMemForcesPresentRepo()
		h := NewForcesPresentHandler(service.NewForcesPresentService(repo))
		app := newForcesPresentTestApp(h, nil)
		id := mustUUIDStringForcesPresent(t, uuidv7.MustBytes())

		resp, _ := doJSONRequestForcesPresent(t, app, http.MethodPatch, "/api/v1/forces-present/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 := newMemForcesPresentRepo()
		h := NewForcesPresentHandler(service.NewForcesPresentService(repo))
		app := newForcesPresentTestApp(h, nil)
		id := mustUUIDStringForcesPresent(t, uuidv7.MustBytes())

		resp, _ := doJSONRequestForcesPresent(t, app, http.MethodPatch, "/api/v1/forces-present/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 := newMemForcesPresentRepo()
		h := NewForcesPresentHandler(service.NewForcesPresentService(repo))
		app := newForcesPresentTestApp(h, nil)
		id := mustUUIDStringForcesPresent(t, uuidv7.MustBytes())

		resp, _ := doJSONRequestForcesPresent(t, app, http.MethodPatch, "/api/v1/forces-present/update/"+id, []byte(`{"data":{"type":"forces_present","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 := newMemForcesPresentRepo()
		h := NewForcesPresentHandler(service.NewForcesPresentService(repo))
		app := newForcesPresentTestApp(h, nil)
		id := mustUUIDStringForcesPresent(t, uuidv7.MustBytes())
		other := mustUUIDStringForcesPresent(t, uuidv7.MustBytes())

		resp, _ := doJSONRequestForcesPresent(t, app, http.MethodPatch, "/api/v1/forces-present/update/"+id, []byte(`{"data":{"type":"forces_present","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 := newMemForcesPresentRepo()
		h := NewForcesPresentHandler(service.NewForcesPresentService(repo))
		app := newForcesPresentTestApp(h, nil)
		id := mustUUIDStringForcesPresent(t, uuidv7.MustBytes())

		resp, _ := doJSONRequestForcesPresent(t, app, http.MethodPatch, "/api/v1/forces-present/update/"+id, []byte(`{"data":{"type":"forces_present","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 := newMemForcesPresentRepo()
		h := NewForcesPresentHandler(service.NewForcesPresentService(repo))
		app := newForcesPresentTestApp(h, nil)
		id := mustUUIDStringForcesPresent(t, uuidv7.MustBytes())

		resp, _ := doJSONRequestForcesPresent(t, app, http.MethodPatch, "/api/v1/forces-present/update/"+id, []byte(`{"data":{"type":"forces_present","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 := newMemForcesPresentRepo()
		id := uuidv7.MustBytes()
		repo.rows[string(id)] = &forces_present.ForcesPresent{ID: id, Name: "Old"}
		h := NewForcesPresentHandler(service.NewForcesPresentService(repo))
		app := newForcesPresentTestApp(h, nil)
		idStr := mustUUIDStringForcesPresent(t, id)

		resp, _ := doJSONRequestForcesPresent(t, app, http.MethodPatch, "/api/v1/forces-present/update/"+idStr, []byte(`{"data":{"type":"forces_present","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 := newMemForcesPresentRepo()
		id := uuidv7.MustBytes()
		repo.rows[string(id)] = &forces_present.ForcesPresent{ID: id, Name: "Old"}
		repo.updateErr = errors.New("update failed")
		h := NewForcesPresentHandler(service.NewForcesPresentService(repo))
		app := newForcesPresentTestApp(h, nil)
		idStr := mustUUIDStringForcesPresent(t, id)

		resp, _ := doJSONRequestForcesPresent(t, app, http.MethodPatch, "/api/v1/forces-present/update/"+idStr, []byte(`{"data":{"type":"forces_present","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 := newMemForcesPresentRepo()
		id := uuidv7.MustBytes()
		repo.rows[string(id)] = &forces_present.ForcesPresent{ID: id, Name: "Old"}
		h := NewForcesPresentHandler(service.NewForcesPresentService(repo))
		actor := uuidv7.MustBytes()
		app := newForcesPresentTestApp(h, actor)
		idStr := mustUUIDStringForcesPresent(t, id)

		resp, _ := doJSONRequestForcesPresent(t, app, http.MethodPatch, "/api/v1/forces-present/update/"+idStr, []byte(`{"data":{"type":"forces_present","id":"`+idStr+`","attributes":{"name":"New","note":"Desc"}}}`))
		if resp.StatusCode != http.StatusOK {
			t.Fatalf("expected 200, got %d", resp.StatusCode)
		}
		if repo.lastUpdate == nil || repo.lastUpdate.Name != "New" || repo.lastUpdate.Note != "Desc" {
			t.Fatalf("expected updated values")
		}
		if string(repo.lastUpdate.UpdatedBy) != string(actor) {
			t.Fatalf("expected updated_by from actor")
		}
	})

	t.Run("success update sortkey note and is_active", func(t *testing.T) {
		repo := newMemForcesPresentRepo()
		id := uuidv7.MustBytes()
		repo.rows[string(id)] = &forces_present.ForcesPresent{ID: id, Name: "Old", Note: "Old", IsActive: true}
		h := NewForcesPresentHandler(service.NewForcesPresentService(repo))
		app := newForcesPresentTestApp(h, nil)
		idStr := mustUUIDStringForcesPresent(t, id)

		resp, _ := doJSONRequestForcesPresent(t, app, http.MethodPatch, "/api/v1/forces-present/update/"+idStr, []byte(`{"data":{"type":"forces_present","id":"`+idStr+`","attributes":{"sortkey":2,"note":"New note","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.SortKey == nil || *repo.lastUpdate.SortKey != 2 {
			t.Fatalf("expected sortkey updated")
		}
		if repo.lastUpdate.Note != "New note" {
			t.Fatalf("expected note updated")
		}
		if repo.lastUpdate.IsActive {
			t.Fatalf("expected is_active false")
		}
	})

	t.Run("success fallback when refetch fails", func(t *testing.T) {
		repo := newMemForcesPresentRepo()
		id := uuidv7.MustBytes()
		existing := &forces_present.ForcesPresent{ID: id, Name: "Old"}
		repo.getByIDFn = func(_ []byte, call int) (*forces_present.ForcesPresent, error) {
			if call == 1 {
				return existing, nil
			}
			return nil, errors.New("second lookup failed")
		}
		h := NewForcesPresentHandler(service.NewForcesPresentService(repo))
		app := newForcesPresentTestApp(h, nil)
		idStr := mustUUIDStringForcesPresent(t, id)

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

func TestForcesPresentHandlerDelete(t *testing.T) {
	t.Run("invalid uuid", func(t *testing.T) {
		repo := newMemForcesPresentRepo()
		h := NewForcesPresentHandler(service.NewForcesPresentService(repo))
		app := newForcesPresentTestApp(h, nil)

		resp, _ := doJSONRequestForcesPresent(t, app, http.MethodDelete, "/api/v1/forces-present/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 := newMemForcesPresentRepo()
		repo.deleteErr = errors.New("delete failed")
		h := NewForcesPresentHandler(service.NewForcesPresentService(repo))
		app := newForcesPresentTestApp(h, nil)
		id := mustUUIDStringForcesPresent(t, uuidv7.MustBytes())

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

	t.Run("success", func(t *testing.T) {
		repo := newMemForcesPresentRepo()
		h := NewForcesPresentHandler(service.NewForcesPresentService(repo))
		actor := uuidv7.MustBytes()
		app := newForcesPresentTestApp(h, actor)
		id := uuidv7.MustBytes()
		idStr := mustUUIDStringForcesPresent(t, id)

		resp, _ := doJSONRequestForcesPresent(t, app, http.MethodDelete, "/api/v1/forces-present/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 TestForcesPresentHandlerList(t *testing.T) {
	t.Run("list error", func(t *testing.T) {
		repo := newMemForcesPresentRepo()
		repo.listErr = errors.New("list failed")
		h := NewForcesPresentHandler(service.NewForcesPresentService(repo))
		app := newForcesPresentTestApp(h, nil)

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

	t.Run("success with filter name and clamp max", func(t *testing.T) {
		repo := newMemForcesPresentRepo()
		repo.listRows = []forces_present.ForcesPresent{{ID: uuidv7.MustBytes(), Name: "Team A", SortKey: intPtrForcesPresentHandler(3), Note: "On-site", IsActive: true, CreatedAt: time.Now(), UpdatedAt: time.Now()}}
		repo.listTotal = 1
		h := NewForcesPresentHandler(service.NewForcesPresentService(repo))
		app := newForcesPresentTestApp(h, nil)

		resp, _ := doJSONRequestForcesPresent(t, app, http.MethodGet, "/api/v1/forces-present/get-all?filter[name]=abc&page[number]=0&page=0&page[size]=0&limit=101&sort=-sortkey", nil)
		if resp.StatusCode != http.StatusOK {
			t.Fatalf("expected 200, got %d", resp.StatusCode)
		}
		if repo.lastListFilter != "abc" || repo.lastListSort != "is_active DESC, CASE WHEN is_active = 1 AND sortkey IS NOT NULL AND sortkey >= 0 THEN 0 ELSE 1 END ASC, CASE WHEN is_active = 1 AND sortkey IS NOT NULL AND sortkey >= 0 THEN sortkey END DESC, name ASC" || 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 := newMemForcesPresentRepo()
		repo.listRows = []forces_present.ForcesPresent{}
		repo.listTotal = 0
		h := NewForcesPresentHandler(service.NewForcesPresentService(repo))
		app := newForcesPresentTestApp(h, nil)

		resp, _ := doJSONRequestForcesPresent(t, app, http.MethodGet, "/api/v1/forces-present/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 TestForcesPresentHandlerListDatatable(t *testing.T) {
	t.Run("list error", func(t *testing.T) {
		repo := newMemForcesPresentRepo()
		repo.listErr = errors.New("list failed")
		h := NewForcesPresentHandler(service.NewForcesPresentService(repo))
		app := newForcesPresentTestApp(h, nil)

		resp, _ := doJSONRequestForcesPresent(t, app, http.MethodGet, "/api/v1/forces-present/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 := newMemForcesPresentRepo()
		repo.listRows = []forces_present.ForcesPresent{{ID: uuidv7.MustBytes(), Name: "Team A", CreatedAt: time.Now(), UpdatedAt: time.Now()}}
		repo.listTotal = 1
		h := NewForcesPresentHandler(service.NewForcesPresentService(repo))
		app := newForcesPresentTestApp(h, nil)

		resp, _ := doJSONRequestForcesPresent(t, app, http.MethodGet, "/api/v1/forces-present/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 := newMemForcesPresentRepo()
		repo.listRows = []forces_present.ForcesPresent{}
		repo.listTotal = 0
		h := NewForcesPresentHandler(service.NewForcesPresentService(repo))
		app := newForcesPresentTestApp(h, nil)

		resp, _ := doJSONRequestForcesPresent(t, app, http.MethodGet, "/api/v1/forces-present/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 TestForcesPresentResource(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 := &forces_present.ForcesPresent{
		ID:        id,
		Name:      "Team A",
		SortKey:   intPtrForcesPresentHandler(2),
		Note:      "On-site",
		IsActive:  true,
		CreatedAt: now,
		CreatedBy: createdBy,
		UpdatedAt: now,
		UpdatedBy: updatedBy,
		DeletedAt: &deletedAt,
		DeletedBy: deletedBy,
	}

	res := forcesPresentResource(row)
	if res.Type != "forces_present" {
		t.Fatalf("unexpected type: %s", res.Type)
	}
	if res.Attributes.SortKey == nil || *res.Attributes.SortKey != 2 {
		t.Fatalf("expected sortkey in resource")
	}
	if res.Attributes.Note != "On-site" || !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.CreatedAt == "" || res.Attributes.UpdatedAt == "" || res.Attributes.DeletedAt == "" {
		t.Fatalf("expected time fields in resource")
	}
}

func intPtrForcesPresentHandler(v int) *int { return &v }
