package handlers

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

	"github.com/gofiber/fiber/v2"

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

type memOpcRepo struct {
	rows map[string]*opc.Opc

	createErr  error
	updateErr  error
	deleteErr  error
	getByIDErr error
	listErr    error

	listRows  []opc.Opc
	listTotal int64

	getByIDFn func(id []byte, call int) (*opc.Opc, error)
	getCalls  int

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

func newMemOpcRepo() *memOpcRepo {
	return &memOpcRepo{
		rows: map[string]*opc.Opc{},
	}
}

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

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

func doJSONRequest(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 mustUUIDString(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 TestNewOpcHandler(t *testing.T) {
	h := NewOpcHandler(service.NewOpcService(newMemOpcRepo()))
	if h == nil || h.validate == nil {
		t.Fatalf("expected handler and validator initialized")
	}
}

func TestOpcHandlerCreate(t *testing.T) {
	t.Run("invalid json", func(t *testing.T) {
		repo := newMemOpcRepo()
		h := NewOpcHandler(service.NewOpcService(repo))
		app := newOpcTestApp(h, nil)

		resp, _ := doJSONRequest(t, app, http.MethodPost, "/api/v1/opc/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 := newMemOpcRepo()
		h := NewOpcHandler(service.NewOpcService(repo))
		app := newOpcTestApp(h, nil)

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

	t.Run("title empty", func(t *testing.T) {
		repo := newMemOpcRepo()
		h := NewOpcHandler(service.NewOpcService(repo))
		app := newOpcTestApp(h, nil)

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

	t.Run("create error", func(t *testing.T) {
		repo := newMemOpcRepo()
		repo.createErr = errors.New("create failed")
		h := NewOpcHandler(service.NewOpcService(repo))
		app := newOpcTestApp(h, nil)

		body := []byte(`{"data":{"type":"opc","attributes":{"title":"Main"}}}`)
		resp, _ := doJSONRequest(t, app, http.MethodPost, "/api/v1/opc/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 := newMemOpcRepo()
		h := NewOpcHandler(service.NewOpcService(repo))
		actor := uuidv7.MustBytes()
		app := newOpcTestApp(h, actor)

		body := []byte(`{"data":{"type":"opc","attributes":{"title":"Main","sortkey":3,"note":"Center","is_active":false}}}`)
		resp, _ := doJSONRequest(t, app, http.MethodPost, "/api/v1/opc/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" {
			t.Fatalf("expected note/description mapped on create")
		}
		if repo.lastCreate.IsActive {
			t.Fatalf("expected is_active=false to be mapped")
		}
		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 := newMemOpcRepo()
		repo.getByIDFn = func(_ []byte, call int) (*opc.Opc, error) {
			if call > 0 {
				return nil, errors.New("lookup failed")
			}
			return nil, nil
		}
		h := NewOpcHandler(service.NewOpcService(repo))
		app := newOpcTestApp(h, nil)

		body := []byte(`{"data":{"type":"opc","attributes":{"title":"Main"}}}`)
		resp, _ := doJSONRequest(t, app, http.MethodPost, "/api/v1/opc/create", body)
		if resp.StatusCode != http.StatusCreated {
			t.Fatalf("expected 201, got %d", resp.StatusCode)
		}
	})
}

func TestOpcHandlerUpdate(t *testing.T) {
	t.Run("invalid uuid", func(t *testing.T) {
		repo := newMemOpcRepo()
		h := NewOpcHandler(service.NewOpcService(repo))
		app := newOpcTestApp(h, nil)

		resp, _ := doJSONRequest(t, app, http.MethodPatch, "/api/v1/opc/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 := newMemOpcRepo()
		h := NewOpcHandler(service.NewOpcService(repo))
		app := newOpcTestApp(h, nil)
		id := mustUUIDString(t, uuidv7.MustBytes())

		resp, _ := doJSONRequest(t, app, http.MethodPatch, "/api/v1/opc/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 := newMemOpcRepo()
		h := NewOpcHandler(service.NewOpcService(repo))
		app := newOpcTestApp(h, nil)
		id := mustUUIDString(t, uuidv7.MustBytes())

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

	t.Run("id required", func(t *testing.T) {
		repo := newMemOpcRepo()
		h := NewOpcHandler(service.NewOpcService(repo))
		app := newOpcTestApp(h, nil)
		id := mustUUIDString(t, uuidv7.MustBytes())

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

	t.Run("id mismatch", func(t *testing.T) {
		repo := newMemOpcRepo()
		h := NewOpcHandler(service.NewOpcService(repo))
		app := newOpcTestApp(h, nil)
		id := mustUUIDString(t, uuidv7.MustBytes())
		other := mustUUIDString(t, uuidv7.MustBytes())

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

	t.Run("no attributes", func(t *testing.T) {
		repo := newMemOpcRepo()
		h := NewOpcHandler(service.NewOpcService(repo))
		app := newOpcTestApp(h, nil)
		id := mustUUIDString(t, uuidv7.MustBytes())

		resp, _ := doJSONRequest(t, app, http.MethodPatch, "/api/v1/opc/update/"+id, []byte(`{"data":{"type":"opc","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 := newMemOpcRepo()
		h := NewOpcHandler(service.NewOpcService(repo))
		app := newOpcTestApp(h, nil)
		id := mustUUIDString(t, uuidv7.MustBytes())

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

	t.Run("title empty", func(t *testing.T) {
		repo := newMemOpcRepo()
		id := uuidv7.MustBytes()
		repo.rows[string(id)] = &opc.Opc{ID: id, Title: "Old"}
		h := NewOpcHandler(service.NewOpcService(repo))
		app := newOpcTestApp(h, nil)
		idStr := mustUUIDString(t, id)

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

	t.Run("update error", func(t *testing.T) {
		repo := newMemOpcRepo()
		id := uuidv7.MustBytes()
		repo.rows[string(id)] = &opc.Opc{ID: id, Title: "Old"}
		repo.updateErr = errors.New("update failed")
		h := NewOpcHandler(service.NewOpcService(repo))
		app := newOpcTestApp(h, nil)
		idStr := mustUUIDString(t, id)

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

	t.Run("success with refetch", func(t *testing.T) {
		repo := newMemOpcRepo()
		id := uuidv7.MustBytes()
		repo.rows[string(id)] = &opc.Opc{ID: id, Title: "Old"}
		h := NewOpcHandler(service.NewOpcService(repo))
		actor := uuidv7.MustBytes()
		app := newOpcTestApp(h, actor)
		idStr := mustUUIDString(t, id)

		resp, _ := doJSONRequest(t, app, http.MethodPatch, "/api/v1/opc/update/"+idStr, []byte(`{"data":{"type":"opc","id":"`+idStr+`","attributes":{"title":"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.Title != "New" {
			t.Fatalf("expected updated values")
		}
		if repo.lastUpdate.SortKey == nil || *repo.lastUpdate.SortKey != 7 || repo.lastUpdate.Note != "Desc" {
			t.Fatalf("expected sortkey/note updated values")
		}
		if repo.lastUpdate.IsActive {
			t.Fatalf("expected is_active=false updated")
		}
		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 := newMemOpcRepo()
		id := uuidv7.MustBytes()
		existing := &opc.Opc{ID: id, Title: "Old"}
		repo.getByIDFn = func(_ []byte, call int) (*opc.Opc, error) {
			if call == 1 {
				return existing, nil
			}
			return nil, errors.New("second lookup failed")
		}
		h := NewOpcHandler(service.NewOpcService(repo))
		app := newOpcTestApp(h, nil)
		idStr := mustUUIDString(t, id)

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

func TestOpcHandlerDelete(t *testing.T) {
	t.Run("invalid uuid", func(t *testing.T) {
		repo := newMemOpcRepo()
		h := NewOpcHandler(service.NewOpcService(repo))
		app := newOpcTestApp(h, nil)

		resp, _ := doJSONRequest(t, app, http.MethodDelete, "/api/v1/opc/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 := newMemOpcRepo()
		repo.deleteErr = errors.New("delete failed")
		h := NewOpcHandler(service.NewOpcService(repo))
		app := newOpcTestApp(h, nil)
		id := mustUUIDString(t, uuidv7.MustBytes())

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

	t.Run("success", func(t *testing.T) {
		repo := newMemOpcRepo()
		h := NewOpcHandler(service.NewOpcService(repo))
		actor := uuidv7.MustBytes()
		app := newOpcTestApp(h, actor)
		id := uuidv7.MustBytes()
		idStr := mustUUIDString(t, id)

		resp, _ := doJSONRequest(t, app, http.MethodDelete, "/api/v1/opc/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 TestOpcHandlerList(t *testing.T) {
	t.Run("list error", func(t *testing.T) {
		repo := newMemOpcRepo()
		repo.listErr = errors.New("list failed")
		h := NewOpcHandler(service.NewOpcService(repo))
		app := newOpcTestApp(h, nil)

		resp, _ := doJSONRequest(t, app, http.MethodGet, "/api/v1/opc/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 := newMemOpcRepo()
		repo.listRows = []opc.Opc{{ID: uuidv7.MustBytes(), Title: "A", CreatedAt: time.Now(), UpdatedAt: time.Now()}}
		repo.listTotal = 1
		h := NewOpcHandler(service.NewOpcService(repo))
		app := newOpcTestApp(h, nil)

		resp, _ := doJSONRequest(t, app, http.MethodGet, "/api/v1/opc/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 := newMemOpcRepo()
		repo.listRows = []opc.Opc{}
		repo.listTotal = 0
		h := NewOpcHandler(service.NewOpcService(repo))
		app := newOpcTestApp(h, nil)

		resp, _ := doJSONRequest(t, app, http.MethodGet, "/api/v1/opc/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 TestOpcHandlerListDatatable(t *testing.T) {
	t.Run("list error", func(t *testing.T) {
		repo := newMemOpcRepo()
		repo.listErr = errors.New("list failed")
		h := NewOpcHandler(service.NewOpcService(repo))
		app := newOpcTestApp(h, nil)

		resp, _ := doJSONRequest(t, app, http.MethodGet, "/api/v1/opc/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 := newMemOpcRepo()
		repo.listRows = []opc.Opc{{ID: uuidv7.MustBytes(), Title: "A", CreatedAt: time.Now(), UpdatedAt: time.Now()}}
		repo.listTotal = 1
		h := NewOpcHandler(service.NewOpcService(repo))
		app := newOpcTestApp(h, nil)

		resp, _ := doJSONRequest(t, app, http.MethodGet, "/api/v1/opc/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 := newMemOpcRepo()
		repo.listRows = []opc.Opc{}
		repo.listTotal = 0
		h := NewOpcHandler(service.NewOpcService(repo))
		app := newOpcTestApp(h, nil)

		resp, _ := doJSONRequest(t, app, http.MethodGet, "/api/v1/opc/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 TestOpcResource(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 := &opc.Opc{
		ID:        id,
		Title:     "Main",
		SortKey:   intPtrOpcHandler(5),
		Note:      "Center",
		IsActive:  true,
		CreatedAt: now,
		CreatedBy: createdBy,
		UpdatedAt: now,
		UpdatedBy: updatedBy,
		DeletedAt: &deletedAt,
		DeletedBy: deletedBy,
	}

	res := opcResource(row)
	if res.Type != "opc" {
		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.IsActive {
		t.Fatalf("expected is_active mapped")
	}
	if res.Attributes.SortKey == nil || *res.Attributes.SortKey != 5 || res.Attributes.Note != "Center" {
		t.Fatalf("expected sortkey/note mapped")
	}
	if res.Attributes.CreatedAt == "" || res.Attributes.UpdatedAt == "" || res.Attributes.DeletedAt == "" {
		t.Fatalf("expected time fields in resource")
	}
}

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