package handlers

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

	"github.com/gofiber/fiber/v2"

	"wucher/internal/domain/federal_state"
	"wucher/internal/domain/land"
	"wucher/internal/service"
	"wucher/internal/shared/pkg/uuidv7"
)

type memFederalStateRepo struct {
	rows map[string]*federal_state.FederalState

	createErr  error
	updateErr  error
	deleteErr  error
	getByIDErr error
	listErr    error

	listRows  []federal_state.FederalState
	listTotal int64

	getByIDFn func(id []byte, call int) (*federal_state.FederalState, error)
	getCalls  int

	lastCreate     *federal_state.FederalState
	lastUpdate     *federal_state.FederalState
	lastDeleteID   []byte
	lastDeleteBy   []byte
	lastListFilter string
	lastListSort   string
	lastListLimit  int
	lastListOffset int
	lastListLandID []byte
	lastLandName   string
}

func newMemFederalStateRepo() *memFederalStateRepo {
	return &memFederalStateRepo{
		rows: map[string]*federal_state.FederalState{},
	}
}

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

func (r *memFederalStateRepo) 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 *memFederalStateRepo) GetByID(_ context.Context, id []byte) (*federal_state.FederalState, 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 *memFederalStateRepo) List(_ context.Context, filter, sort string, limit, offset int, landID []byte, landName string) ([]federal_state.FederalState, int64, error) {
	r.lastListFilter = filter
	r.lastListSort = sort
	r.lastListLimit = limit
	r.lastListOffset = offset
	r.lastListLandID = append([]byte(nil), landID...)
	r.lastLandName = landName
	if r.listErr != nil {
		return nil, 0, r.listErr
	}
	return r.listRows, r.listTotal, nil
}

func newFederalStateTestApp(h *FederalStateHandler, 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/federal-state/create", h.Create)
	app.Patch("/api/v1/federal-state/update/:id", h.Update)
	app.Delete("/api/v1/federal-state/delete/:id", h.Delete)
	app.Get("/api/v1/federal-state/get-all", h.List)
	app.Get("/api/v1/federal-state/get-all/dt", h.ListDatatable)
	return app
}

func doJSONRequestFederalState(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 mustUUIDStringFederalState(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 TestNewFederalStateHandler(t *testing.T) {
	h := NewFederalStateHandler(service.NewFederalStateService(newMemFederalStateRepo()))
	if h == nil || h.validate == nil {
		t.Fatalf("expected handler and validator initialized")
	}
}

func TestFederalStateHandlerCreate(t *testing.T) {
	t.Run("invalid json", func(t *testing.T) {
		repo := newMemFederalStateRepo()
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		app := newFederalStateTestApp(h, nil)

		resp, _ := doJSONRequestFederalState(t, app, http.MethodPost, "/api/v1/federal-state/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 := newMemFederalStateRepo()
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		app := newFederalStateTestApp(h, nil)

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

	t.Run("name empty", func(t *testing.T) {
		repo := newMemFederalStateRepo()
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		app := newFederalStateTestApp(h, nil)

		body := []byte(`{"data":{"type":"federal_state","attributes":{"name":"  ","land_id":"019df658-8b00-74ce-9db0-2bdae4ea15fb"}}}`)
		resp, _ := doJSONRequestFederalState(t, app, http.MethodPost, "/api/v1/federal-state/create", body)
		if resp.StatusCode != http.StatusUnprocessableEntity {
			t.Fatalf("expected 422, got %d", resp.StatusCode)
		}
	})

	t.Run("create error", func(t *testing.T) {
		repo := newMemFederalStateRepo()
		repo.createErr = errors.New("create failed")
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		app := newFederalStateTestApp(h, nil)

		body := []byte(`{"data":{"type":"federal_state","attributes":{"name":"Main","land_id":"019df658-8b00-74ce-9db0-2bdae4ea15fb"}}}`)
		resp, _ := doJSONRequestFederalState(t, app, http.MethodPost, "/api/v1/federal-state/create", body)
		if resp.StatusCode != http.StatusBadRequest {
			t.Fatalf("expected 400, got %d", resp.StatusCode)
		}
	})

	t.Run("invalid land_id", func(t *testing.T) {
		repo := newMemFederalStateRepo()
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		app := newFederalStateTestApp(h, nil)

		body := []byte(`{"data":{"type":"federal_state","attributes":{"name":"Main","land_id":"not-uuid"}}}`)
		resp, _ := doJSONRequestFederalState(t, app, http.MethodPost, "/api/v1/federal-state/create", body)
		if resp.StatusCode != http.StatusUnprocessableEntity {
			t.Fatalf("expected 422, got %d", resp.StatusCode)
		}
	})

	t.Run("success with refetch", func(t *testing.T) {
		repo := newMemFederalStateRepo()
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		actor := uuidv7.MustBytes()
		app := newFederalStateTestApp(h, actor)

		body := []byte(`{"data":{"type":"federal_state","attributes":{"name":"Main","note":"  Important note  ","land_id":"019df658-8b00-74ce-9db0-2bdae4ea15fb","sortkey":9,"is_active":false}}}`)
		resp, _ := doJSONRequestFederalState(t, app, http.MethodPost, "/api/v1/federal-state/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 len(repo.lastCreate.LandID) == 0 {
			t.Fatalf("expected land_id mapped")
		}
		if repo.lastCreate.SortKey == nil || *repo.lastCreate.SortKey != 9 || repo.lastCreate.IsActive {
			t.Fatalf("expected sortkey/is_active mapped correctly")
		}
		if repo.lastCreate.Note != "Important note" {
			t.Fatalf("expected note mapped and trimmed")
		}
		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 clear sortkey with null", func(t *testing.T) {
		repo := newMemFederalStateRepo()
		id := uuidv7.MustBytes()
		repo.rows[string(id)] = &federal_state.FederalState{
			ID:      id,
			Name:    "Old",
			LandID:  uuidv7.MustBytes(),
			SortKey: intPtr(7),
		}
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		app := newFederalStateTestApp(h, nil)
		idStr := mustUUIDStringFederalState(t, id)

		resp, _ := doJSONRequestFederalState(t, app, http.MethodPatch, "/api/v1/federal-state/update/"+idStr, []byte(`{"data":{"type":"federal_state","id":"`+idStr+`","attributes":{"sortkey":null}}}`))
		if resp.StatusCode != http.StatusOK {
			t.Fatalf("expected 200, got %d", resp.StatusCode)
		}
		if repo.lastUpdate == nil || repo.lastUpdate.SortKey != nil {
			t.Fatalf("expected sortkey cleared")
		}
	})

	t.Run("success fallback when refetch error", func(t *testing.T) {
		repo := newMemFederalStateRepo()
		repo.getByIDFn = func(_ []byte, call int) (*federal_state.FederalState, error) {
			if call > 0 {
				return nil, errors.New("lookup failed")
			}
			return nil, nil
		}
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		app := newFederalStateTestApp(h, nil)

		body := []byte(`{"data":{"type":"federal_state","attributes":{"name":"Main","land_id":"019df658-8b00-74ce-9db0-2bdae4ea15fb"}}}`)
		resp, _ := doJSONRequestFederalState(t, app, http.MethodPost, "/api/v1/federal-state/create", body)
		if resp.StatusCode != http.StatusCreated {
			t.Fatalf("expected 201, got %d", resp.StatusCode)
		}
	})
}

func TestFederalStateHandlerUpdate(t *testing.T) {
	t.Run("invalid uuid", func(t *testing.T) {
		repo := newMemFederalStateRepo()
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		app := newFederalStateTestApp(h, nil)

		resp, _ := doJSONRequestFederalState(t, app, http.MethodPatch, "/api/v1/federal-state/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 := newMemFederalStateRepo()
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		app := newFederalStateTestApp(h, nil)
		id := mustUUIDStringFederalState(t, uuidv7.MustBytes())

		resp, _ := doJSONRequestFederalState(t, app, http.MethodPatch, "/api/v1/federal-state/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 := newMemFederalStateRepo()
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		app := newFederalStateTestApp(h, nil)
		id := mustUUIDStringFederalState(t, uuidv7.MustBytes())

		resp, _ := doJSONRequestFederalState(t, app, http.MethodPatch, "/api/v1/federal-state/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 := newMemFederalStateRepo()
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		app := newFederalStateTestApp(h, nil)
		id := mustUUIDStringFederalState(t, uuidv7.MustBytes())

		resp, _ := doJSONRequestFederalState(t, app, http.MethodPatch, "/api/v1/federal-state/update/"+id, []byte(`{"data":{"type":"federal_state","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 := newMemFederalStateRepo()
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		app := newFederalStateTestApp(h, nil)
		id := mustUUIDStringFederalState(t, uuidv7.MustBytes())
		other := mustUUIDStringFederalState(t, uuidv7.MustBytes())

		resp, _ := doJSONRequestFederalState(t, app, http.MethodPatch, "/api/v1/federal-state/update/"+id, []byte(`{"data":{"type":"federal_state","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 := newMemFederalStateRepo()
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		app := newFederalStateTestApp(h, nil)
		id := mustUUIDStringFederalState(t, uuidv7.MustBytes())

		resp, _ := doJSONRequestFederalState(t, app, http.MethodPatch, "/api/v1/federal-state/update/"+id, []byte(`{"data":{"type":"federal_state","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 := newMemFederalStateRepo()
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		app := newFederalStateTestApp(h, nil)
		id := mustUUIDStringFederalState(t, uuidv7.MustBytes())

		resp, _ := doJSONRequestFederalState(t, app, http.MethodPatch, "/api/v1/federal-state/update/"+id, []byte(`{"data":{"type":"federal_state","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 := newMemFederalStateRepo()
		id := uuidv7.MustBytes()
		repo.rows[string(id)] = &federal_state.FederalState{ID: id, Name: "Old"}
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		app := newFederalStateTestApp(h, nil)
		idStr := mustUUIDStringFederalState(t, id)

		resp, _ := doJSONRequestFederalState(t, app, http.MethodPatch, "/api/v1/federal-state/update/"+idStr, []byte(`{"data":{"type":"federal_state","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 := newMemFederalStateRepo()
		id := uuidv7.MustBytes()
		repo.rows[string(id)] = &federal_state.FederalState{ID: id, Name: "Old"}
		repo.updateErr = errors.New("update failed")
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		app := newFederalStateTestApp(h, nil)
		idStr := mustUUIDStringFederalState(t, id)

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

	t.Run("invalid land_id", func(t *testing.T) {
		repo := newMemFederalStateRepo()
		id := uuidv7.MustBytes()
		repo.rows[string(id)] = &federal_state.FederalState{ID: id, Name: "Old"}
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		app := newFederalStateTestApp(h, nil)
		idStr := mustUUIDStringFederalState(t, id)

		resp, _ := doJSONRequestFederalState(t, app, http.MethodPatch, "/api/v1/federal-state/update/"+idStr, []byte(`{"data":{"type":"federal_state","id":"`+idStr+`","attributes":{"land_id":"not-uuid"}}}`))
		if resp.StatusCode != http.StatusUnprocessableEntity {
			t.Fatalf("expected 422, got %d", resp.StatusCode)
		}
	})

	t.Run("success with refetch", func(t *testing.T) {
		repo := newMemFederalStateRepo()
		id := uuidv7.MustBytes()
		repo.rows[string(id)] = &federal_state.FederalState{ID: id, Name: "Old"}
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		actor := uuidv7.MustBytes()
		app := newFederalStateTestApp(h, actor)
		idStr := mustUUIDStringFederalState(t, id)

		resp, _ := doJSONRequestFederalState(t, app, http.MethodPatch, "/api/v1/federal-state/update/"+idStr, []byte(`{"data":{"type":"federal_state","id":"`+idStr+`","attributes":{"name":"New","note":"  Updated note  ","land_id":"019df658-8b00-74ce-9db0-2bdae4ea15fb","sortkey":2,"is_active":false}}}`))
		if resp.StatusCode != http.StatusOK {
			t.Fatalf("expected 200, got %d", resp.StatusCode)
		}
		if repo.lastUpdate == nil || repo.lastUpdate.Name != "New" {
			t.Fatalf("expected updated values")
		}
		if len(repo.lastUpdate.LandID) == 0 {
			t.Fatalf("expected land_id updated")
		}
		if repo.lastUpdate.SortKey == nil || *repo.lastUpdate.SortKey != 2 || repo.lastUpdate.IsActive {
			t.Fatalf("expected sortkey/is_active updated")
		}
		if repo.lastUpdate.Note != "Updated note" {
			t.Fatalf("expected note updated and trimmed")
		}
		if string(repo.lastUpdate.UpdatedBy) != string(actor) {
			t.Fatalf("expected updated_by from actor")
		}
	})

	t.Run("success change land_id clears stale land association", func(t *testing.T) {
		repo := newMemFederalStateRepo()
		id := uuidv7.MustBytes()
		oldLandID := uuidv7.MustBytes()
		repo.rows[string(id)] = &federal_state.FederalState{
			ID:     id,
			Name:   "Old",
			LandID: oldLandID,
			Land:   &land.Land{ID: oldLandID, Name: "Old Land"},
		}
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		app := newFederalStateTestApp(h, nil)
		idStr := mustUUIDStringFederalState(t, id)
		newLandID := mustUUIDStringFederalState(t, uuidv7.MustBytes())

		resp, _ := doJSONRequestFederalState(t, app, http.MethodPatch, "/api/v1/federal-state/update/"+idStr, []byte(`{"data":{"type":"federal_state","id":"`+idStr+`","attributes":{"land_id":"`+newLandID+`"}}}`))
		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.Land != nil {
			t.Fatalf("expected stale land association cleared when land_id changes")
		}
	})

	t.Run("success fallback when refetch fails", func(t *testing.T) {
		repo := newMemFederalStateRepo()
		id := uuidv7.MustBytes()
		existing := &federal_state.FederalState{ID: id, Name: "Old"}
		repo.getByIDFn = func(_ []byte, call int) (*federal_state.FederalState, error) {
			if call == 1 {
				return existing, nil
			}
			return nil, errors.New("second lookup failed")
		}
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		app := newFederalStateTestApp(h, nil)
		idStr := mustUUIDStringFederalState(t, id)

		resp, _ := doJSONRequestFederalState(t, app, http.MethodPatch, "/api/v1/federal-state/update/"+idStr, []byte(`{"data":{"type":"federal_state","id":"`+idStr+`","attributes":{"name":"Only","land_id":"019df658-8b00-74ce-9db0-2bdae4ea15fb"}}}`))
		if resp.StatusCode != http.StatusOK {
			t.Fatalf("expected 200, got %d", resp.StatusCode)
		}
	})
}

func TestFederalStateHandlerDelete(t *testing.T) {
	t.Run("invalid uuid", func(t *testing.T) {
		repo := newMemFederalStateRepo()
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		app := newFederalStateTestApp(h, nil)

		resp, _ := doJSONRequestFederalState(t, app, http.MethodDelete, "/api/v1/federal-state/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 := newMemFederalStateRepo()
		repo.deleteErr = errors.New("delete failed")
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		app := newFederalStateTestApp(h, nil)
		id := mustUUIDStringFederalState(t, uuidv7.MustBytes())

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

	t.Run("success", func(t *testing.T) {
		repo := newMemFederalStateRepo()
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		actor := uuidv7.MustBytes()
		app := newFederalStateTestApp(h, actor)
		id := uuidv7.MustBytes()
		idStr := mustUUIDStringFederalState(t, id)

		resp, _ := doJSONRequestFederalState(t, app, http.MethodDelete, "/api/v1/federal-state/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 TestFederalStateHandlerList(t *testing.T) {
	t.Run("list error", func(t *testing.T) {
		repo := newMemFederalStateRepo()
		repo.listErr = errors.New("list failed")
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		app := newFederalStateTestApp(h, nil)

		resp, _ := doJSONRequestFederalState(t, app, http.MethodGet, "/api/v1/federal-state/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 := newMemFederalStateRepo()
		repo.listRows = []federal_state.FederalState{{ID: uuidv7.MustBytes(), Name: "A", CreatedAt: time.Now(), UpdatedAt: time.Now()}}
		repo.listTotal = 1
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		app := newFederalStateTestApp(h, nil)

		resp, _ := doJSONRequestFederalState(t, app, http.MethodGet, "/api/v1/federal-state/get-all?filter[name]=abc&page[number]=0&page[size]=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 filter search and pagination", func(t *testing.T) {
		repo := newMemFederalStateRepo()
		repo.listRows = []federal_state.FederalState{}
		repo.listTotal = 0
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		app := newFederalStateTestApp(h, nil)

		resp, _ := doJSONRequestFederalState(t, app, http.MethodGet, "/api/v1/federal-state/get-all?filter[search]=needle&page[number]=2&page[size]=20", 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)
		}
	})

	t.Run("invalid land_id", func(t *testing.T) {
		repo := newMemFederalStateRepo()
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		app := newFederalStateTestApp(h, nil)

		resp, _ := doJSONRequestFederalState(t, app, http.MethodGet, "/api/v1/federal-state/get-all?land_id=not-uuid", nil)
		if resp.StatusCode != http.StatusUnprocessableEntity {
			t.Fatalf("expected 422, got %d", resp.StatusCode)
		}
	})

	t.Run("land filters forwarded", func(t *testing.T) {
		repo := newMemFederalStateRepo()
		repo.listRows = []federal_state.FederalState{}
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		app := newFederalStateTestApp(h, nil)
		landID := mustUUIDStringFederalState(t, uuidv7.MustBytes())

		resp, _ := doJSONRequestFederalState(t, app, http.MethodGet, "/api/v1/federal-state/get-all?filter[land_name]=Ger&land_id="+landID, nil)
		if resp.StatusCode != http.StatusOK {
			t.Fatalf("expected 200, got %d", resp.StatusCode)
		}
		if len(repo.lastListLandID) == 0 || repo.lastLandName != "Ger" {
			t.Fatalf("expected land filter mapped")
		}
	})
}

func TestFederalStateHandlerListDatatable(t *testing.T) {
	t.Run("list error", func(t *testing.T) {
		repo := newMemFederalStateRepo()
		repo.listErr = errors.New("list failed")
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		app := newFederalStateTestApp(h, nil)

		resp, _ := doJSONRequestFederalState(t, app, http.MethodGet, "/api/v1/federal-state/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 := newMemFederalStateRepo()
		repo.listRows = []federal_state.FederalState{{ID: uuidv7.MustBytes(), Name: "A", CreatedAt: time.Now(), UpdatedAt: time.Now()}}
		repo.listTotal = 1
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		app := newFederalStateTestApp(h, nil)

		resp, _ := doJSONRequestFederalState(t, app, http.MethodGet, "/api/v1/federal-state/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 := newMemFederalStateRepo()
		repo.listRows = []federal_state.FederalState{}
		repo.listTotal = 0
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		app := newFederalStateTestApp(h, nil)

		resp, _ := doJSONRequestFederalState(t, app, http.MethodGet, "/api/v1/federal-state/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)
		}
	})

	t.Run("invalid land_id", func(t *testing.T) {
		repo := newMemFederalStateRepo()
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		app := newFederalStateTestApp(h, nil)

		resp, _ := doJSONRequestFederalState(t, app, http.MethodGet, "/api/v1/federal-state/get-all/dt?land_id=not-uuid", nil)
		if resp.StatusCode != http.StatusUnprocessableEntity {
			t.Fatalf("expected 422, got %d", resp.StatusCode)
		}
	})

	t.Run("land_name direct forwarded", func(t *testing.T) {
		repo := newMemFederalStateRepo()
		repo.listRows = []federal_state.FederalState{}
		h := NewFederalStateHandler(service.NewFederalStateService(repo))
		app := newFederalStateTestApp(h, nil)
		landID := mustUUIDStringFederalState(t, uuidv7.MustBytes())

		resp, _ := doJSONRequestFederalState(t, app, http.MethodGet, "/api/v1/federal-state/get-all/dt?land_name=Germany&land_id="+landID, nil)
		if resp.StatusCode != http.StatusOK {
			t.Fatalf("expected 200, got %d", resp.StatusCode)
		}
		if repo.lastLandName != "Germany" || len(repo.lastListLandID) == 0 {
			t.Fatalf("expected land_name and land_id forwarded")
		}
	})
}

func TestFederalStateResource(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 := &federal_state.FederalState{
		ID:        id,
		Name:      "Main",
		Note:      "Important note",
		LandID:    uuidv7.MustBytes(),
		Land:      &land.Land{Name: "Germany", LandISOCode: "DE"},
		SortKey:   intPtr(4),
		IsActive:  true,
		CreatedAt: now,
		CreatedBy: createdBy,
		UpdatedAt: now,
		UpdatedBy: updatedBy,
		DeletedAt: &deletedAt,
		DeletedBy: deletedBy,
	}

	res := federalStateResource(row)
	if res.Type != "federal_state" {
		t.Fatalf("unexpected type: %s", res.Type)
	}
	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")
	}
	if res.Attributes.SortKey == nil || *res.Attributes.SortKey != 4 || !res.Attributes.IsActive {
		t.Fatalf("expected sortkey/is_active in resource")
	}
	if res.Attributes.LandID == "" {
		t.Fatalf("expected land_id in resource")
	}
	if res.Attributes.LandName != "Germany" || res.Attributes.LandISOCode != "DE" {
		t.Fatalf("expected land preload fields in resource")
	}
	if res.Attributes.Note != "Important note" {
		t.Fatalf("expected note in resource")
	}
}
