package handlers import ( "bytes" "context" "errors" "io" "net/http" "testing" "time" "github.com/gofiber/fiber/v2" "wucher/internal/domain/vocation" "wucher/internal/service" "wucher/internal/shared/pkg/uuidv7" ) type memVocationRepo struct { rows map[string]*vocation.Vocation createErr error updateErr error deleteErr error getByIDErr error listErr error listRows []vocation.Vocation listTotal int64 getByIDFn func(id []byte, call int) (*vocation.Vocation, error) getCalls int lastCreate *vocation.Vocation lastUpdate *vocation.Vocation lastDeleteID []byte lastDeleteBy []byte lastListFilter string lastListSort string lastListLimit int lastListOffset int } func newMemVocationRepo() *memVocationRepo { return &memVocationRepo{ rows: map[string]*vocation.Vocation{}, } } func (r *memVocationRepo) Create(_ context.Context, row *vocation.Vocation) 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 *memVocationRepo) Update(_ context.Context, row *vocation.Vocation) error { if r.updateErr != nil { return r.updateErr } r.rows[string(row.ID)] = row r.lastUpdate = row return nil } func (r *memVocationRepo) 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 *memVocationRepo) GetByID(_ context.Context, id []byte) (*vocation.Vocation, 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 *memVocationRepo) List(_ context.Context, filter, sort string, limit, offset int) ([]vocation.Vocation, 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 newVocationTestApp(h *VocationHandler, 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/vocation/create", h.Create) app.Patch("/api/v1/vocation/update/:uuid", h.Update) app.Delete("/api/v1/vocation/delete/:uuid", h.Delete) app.Get("/api/v1/vocation/get-all", h.List) app.Get("/api/v1/vocation/get-all/dt", h.ListDatatable) return app } func doJSONRequestVocation(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 mustUUIDStringVocation(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 TestNewVocationHandler(t *testing.T) { h := NewVocationHandler(service.NewVocationService(newMemVocationRepo())) if h == nil || h.validate == nil { t.Fatalf("expected handler and validator initialized") } } func TestVocationHandlerCreate(t *testing.T) { t.Run("invalid json", func(t *testing.T) { repo := newMemVocationRepo() h := NewVocationHandler(service.NewVocationService(repo)) app := newVocationTestApp(h, nil) resp, _ := doJSONRequestVocation(t, app, http.MethodPost, "/api/v1/vocation/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 := newMemVocationRepo() h := NewVocationHandler(service.NewVocationService(repo)) app := newVocationTestApp(h, nil) resp, _ := doJSONRequestVocation(t, app, http.MethodPost, "/api/v1/vocation/create", []byte(`{}`)) if resp.StatusCode != http.StatusUnprocessableEntity { t.Fatalf("expected 422, got %d", resp.StatusCode) } }) t.Run("name empty", func(t *testing.T) { repo := newMemVocationRepo() h := NewVocationHandler(service.NewVocationService(repo)) app := newVocationTestApp(h, nil) body := []byte(`{"data":{"type":"vocation","attributes":{"name":" "}}}`) resp, _ := doJSONRequestVocation(t, app, http.MethodPost, "/api/v1/vocation/create", body) if resp.StatusCode != http.StatusUnprocessableEntity { t.Fatalf("expected 422, got %d", resp.StatusCode) } }) t.Run("create error", func(t *testing.T) { repo := newMemVocationRepo() repo.createErr = errors.New("create failed") h := NewVocationHandler(service.NewVocationService(repo)) app := newVocationTestApp(h, nil) body := []byte(`{"data":{"type":"vocation","attributes":{"name":"Main"}}}`) resp, _ := doJSONRequestVocation(t, app, http.MethodPost, "/api/v1/vocation/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 := newMemVocationRepo() h := NewVocationHandler(service.NewVocationService(repo)) actor := uuidv7.MustBytes() app := newVocationTestApp(h, actor) body := []byte(`{"data":{"type":"vocation","attributes":{"name":"Main","sortkey":3,"note":"Center","is_active":false}}}`) resp, _ := doJSONRequestVocation(t, app, http.MethodPost, "/api/v1/vocation/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.SortKey == nil || *repo.lastCreate.SortKey != 3 { t.Fatalf("expected sortkey mapped on create") } if repo.lastCreate.Note != "Center" || repo.lastCreate.IsActive { t.Fatalf("expected note/description/is_active mapped on create independently") } 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 := newMemVocationRepo() repo.getByIDFn = func(_ []byte, call int) (*vocation.Vocation, error) { if call > 0 { return nil, errors.New("lookup failed") } return nil, nil } h := NewVocationHandler(service.NewVocationService(repo)) app := newVocationTestApp(h, nil) body := []byte(`{"data":{"type":"vocation","attributes":{"name":"Main"}}}`) resp, _ := doJSONRequestVocation(t, app, http.MethodPost, "/api/v1/vocation/create", body) if resp.StatusCode != http.StatusCreated { t.Fatalf("expected 201, got %d", resp.StatusCode) } }) } func TestVocationHandlerUpdate(t *testing.T) { t.Run("invalid uuid", func(t *testing.T) { repo := newMemVocationRepo() h := NewVocationHandler(service.NewVocationService(repo)) app := newVocationTestApp(h, nil) resp, _ := doJSONRequestVocation(t, app, http.MethodPatch, "/api/v1/vocation/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 := newMemVocationRepo() h := NewVocationHandler(service.NewVocationService(repo)) app := newVocationTestApp(h, nil) id := mustUUIDStringVocation(t, uuidv7.MustBytes()) resp, _ := doJSONRequestVocation(t, app, http.MethodPatch, "/api/v1/vocation/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 := newMemVocationRepo() h := NewVocationHandler(service.NewVocationService(repo)) app := newVocationTestApp(h, nil) id := mustUUIDStringVocation(t, uuidv7.MustBytes()) resp, _ := doJSONRequestVocation(t, app, http.MethodPatch, "/api/v1/vocation/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 := newMemVocationRepo() h := NewVocationHandler(service.NewVocationService(repo)) app := newVocationTestApp(h, nil) id := mustUUIDStringVocation(t, uuidv7.MustBytes()) resp, _ := doJSONRequestVocation(t, app, http.MethodPatch, "/api/v1/vocation/update/"+id, []byte(`{"data":{"type":"vocation","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 := newMemVocationRepo() h := NewVocationHandler(service.NewVocationService(repo)) app := newVocationTestApp(h, nil) id := mustUUIDStringVocation(t, uuidv7.MustBytes()) other := mustUUIDStringVocation(t, uuidv7.MustBytes()) resp, _ := doJSONRequestVocation(t, app, http.MethodPatch, "/api/v1/vocation/update/"+id, []byte(`{"data":{"type":"vocation","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 := newMemVocationRepo() h := NewVocationHandler(service.NewVocationService(repo)) app := newVocationTestApp(h, nil) id := mustUUIDStringVocation(t, uuidv7.MustBytes()) resp, _ := doJSONRequestVocation(t, app, http.MethodPatch, "/api/v1/vocation/update/"+id, []byte(`{"data":{"type":"vocation","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 := newMemVocationRepo() h := NewVocationHandler(service.NewVocationService(repo)) app := newVocationTestApp(h, nil) id := mustUUIDStringVocation(t, uuidv7.MustBytes()) resp, _ := doJSONRequestVocation(t, app, http.MethodPatch, "/api/v1/vocation/update/"+id, []byte(`{"data":{"type":"vocation","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 := newMemVocationRepo() id := uuidv7.MustBytes() repo.rows[string(id)] = &vocation.Vocation{ID: id, Name: "Old"} h := NewVocationHandler(service.NewVocationService(repo)) app := newVocationTestApp(h, nil) idStr := mustUUIDStringVocation(t, id) resp, _ := doJSONRequestVocation(t, app, http.MethodPatch, "/api/v1/vocation/update/"+idStr, []byte(`{"data":{"type":"vocation","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 := newMemVocationRepo() id := uuidv7.MustBytes() repo.rows[string(id)] = &vocation.Vocation{ID: id, Name: "Old"} repo.updateErr = errors.New("update failed") h := NewVocationHandler(service.NewVocationService(repo)) app := newVocationTestApp(h, nil) idStr := mustUUIDStringVocation(t, id) resp, _ := doJSONRequestVocation(t, app, http.MethodPatch, "/api/v1/vocation/update/"+idStr, []byte(`{"data":{"type":"vocation","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 := newMemVocationRepo() id := uuidv7.MustBytes() repo.rows[string(id)] = &vocation.Vocation{ID: id, Name: "Old"} h := NewVocationHandler(service.NewVocationService(repo)) actor := uuidv7.MustBytes() app := newVocationTestApp(h, actor) idStr := mustUUIDStringVocation(t, id) resp, _ := doJSONRequestVocation(t, app, http.MethodPatch, "/api/v1/vocation/update/"+idStr, []byte(`{"data":{"type":"vocation","id":"`+idStr+`","attributes":{"name":"New","sortkey":7,"note":"Desc","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 repo.lastUpdate.SortKey == nil || *repo.lastUpdate.SortKey != 7 || repo.lastUpdate.Note != "Desc" || repo.lastUpdate.IsActive { t.Fatalf("expected sortkey/note/is_active updated values") } if string(repo.lastUpdate.UpdatedBy) != string(actor) { t.Fatalf("expected updated_by from actor") } }) t.Run("success fallback when refetch fails", func(t *testing.T) { repo := newMemVocationRepo() id := uuidv7.MustBytes() existing := &vocation.Vocation{ID: id, Name: "Old"} repo.getByIDFn = func(_ []byte, call int) (*vocation.Vocation, error) { if call == 1 { return existing, nil } return nil, errors.New("second lookup failed") } h := NewVocationHandler(service.NewVocationService(repo)) app := newVocationTestApp(h, nil) idStr := mustUUIDStringVocation(t, id) resp, _ := doJSONRequestVocation(t, app, http.MethodPatch, "/api/v1/vocation/update/"+idStr, []byte(`{"data":{"type":"vocation","id":"`+idStr+`","attributes":{"note":"Only note"}}}`)) if resp.StatusCode != http.StatusOK { t.Fatalf("expected 200, got %d", resp.StatusCode) } }) } func TestVocationHandlerDelete(t *testing.T) { t.Run("invalid uuid", func(t *testing.T) { repo := newMemVocationRepo() h := NewVocationHandler(service.NewVocationService(repo)) app := newVocationTestApp(h, nil) resp, _ := doJSONRequestVocation(t, app, http.MethodDelete, "/api/v1/vocation/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 := newMemVocationRepo() repo.deleteErr = errors.New("delete failed") h := NewVocationHandler(service.NewVocationService(repo)) app := newVocationTestApp(h, nil) id := mustUUIDStringVocation(t, uuidv7.MustBytes()) resp, _ := doJSONRequestVocation(t, app, http.MethodDelete, "/api/v1/vocation/delete/"+id, nil) if resp.StatusCode != http.StatusBadRequest { t.Fatalf("expected 400, got %d", resp.StatusCode) } }) t.Run("success", func(t *testing.T) { repo := newMemVocationRepo() h := NewVocationHandler(service.NewVocationService(repo)) actor := uuidv7.MustBytes() app := newVocationTestApp(h, actor) id := uuidv7.MustBytes() idStr := mustUUIDStringVocation(t, id) resp, _ := doJSONRequestVocation(t, app, http.MethodDelete, "/api/v1/vocation/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 TestVocationHandlerList(t *testing.T) { t.Run("list error", func(t *testing.T) { repo := newMemVocationRepo() repo.listErr = errors.New("list failed") h := NewVocationHandler(service.NewVocationService(repo)) app := newVocationTestApp(h, nil) resp, _ := doJSONRequestVocation(t, app, http.MethodGet, "/api/v1/vocation/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 := newMemVocationRepo() repo.listRows = []vocation.Vocation{{ID: uuidv7.MustBytes(), Name: "A", CreatedAt: time.Now(), UpdatedAt: time.Now()}} repo.listTotal = 1 h := NewVocationHandler(service.NewVocationService(repo)) app := newVocationTestApp(h, nil) resp, _ := doJSONRequestVocation(t, app, http.MethodGet, "/api/v1/vocation/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 := newMemVocationRepo() repo.listRows = []vocation.Vocation{} repo.listTotal = 0 h := NewVocationHandler(service.NewVocationService(repo)) app := newVocationTestApp(h, nil) resp, _ := doJSONRequestVocation(t, app, http.MethodGet, "/api/v1/vocation/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 TestVocationHandlerListDatatable(t *testing.T) { t.Run("list error", func(t *testing.T) { repo := newMemVocationRepo() repo.listErr = errors.New("list failed") h := NewVocationHandler(service.NewVocationService(repo)) app := newVocationTestApp(h, nil) resp, _ := doJSONRequestVocation(t, app, http.MethodGet, "/api/v1/vocation/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 := newMemVocationRepo() repo.listRows = []vocation.Vocation{{ID: uuidv7.MustBytes(), Name: "A", CreatedAt: time.Now(), UpdatedAt: time.Now()}} repo.listTotal = 1 h := NewVocationHandler(service.NewVocationService(repo)) app := newVocationTestApp(h, nil) resp, _ := doJSONRequestVocation(t, app, http.MethodGet, "/api/v1/vocation/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 := newMemVocationRepo() repo.listRows = []vocation.Vocation{} repo.listTotal = 0 h := NewVocationHandler(service.NewVocationService(repo)) app := newVocationTestApp(h, nil) resp, _ := doJSONRequestVocation(t, app, http.MethodGet, "/api/v1/vocation/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 TestVocationResource(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 := &vocation.Vocation{ ID: id, Name: "Main", SortKey: intPtrVocationHandler(5), Note: "Center", IsActive: true, CreatedAt: now, CreatedBy: createdBy, UpdatedAt: now, UpdatedBy: updatedBy, DeletedAt: &deletedAt, DeletedBy: deletedBy, } res := vocationResource(row) if res.Type != "vocation" { 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.SortKey == nil || *res.Attributes.SortKey != 5 || res.Attributes.Note != "Center" || !res.Attributes.IsActive { t.Fatalf("expected sortkey/note/is_active fields in resource") } if res.Attributes.CreatedAt == "" || res.Attributes.UpdatedAt == "" || res.Attributes.DeletedAt == "" { t.Fatalf("expected time fields in resource") } } func intPtrVocationHandler(v int) *int { return &v }