package api

import (
	"context"
	"errors"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/go-chi/chi/v5"
	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgtype"
)

type fakeRow struct {
	ID   pgtype.UUID
	Name string
}

func reqWithParam(_ *testing.T, key, value string) *http.Request {
	r := httptest.NewRequest("GET", "/", nil)
	rctx := chi.NewRouteContext()
	rctx.URLParams.Add(key, value)
	return r.WithContext(context.WithValue(r.Context(), chi.RouteCtxKey, rctx))
}

func TestResolveByID_InvalidUUID(t *testing.T) {
	called := 0
	fetch := func(_ context.Context, _ pgtype.UUID) (fakeRow, error) {
		called++
		return fakeRow{}, nil
	}
	r := reqWithParam(t, "id", "not-a-uuid")
	row, apiErr := resolveByID(r, "id", fetch, "track")
	if apiErr == nil {
		t.Fatalf("expected apiErr, got nil (row=%+v)", row)
	}
	if apiErr.Status != 400 {
		t.Errorf("Status: got %d, want 400", apiErr.Status)
	}
	if apiErr.Code != "bad_request" {
		t.Errorf("Code: got %q, want %q", apiErr.Code, "bad_request")
	}
	if called != 0 {
		t.Errorf("fetch was called %d times; expected 0", called)
	}
}

func TestResolveByID_NotFound(t *testing.T) {
	fetch := func(_ context.Context, _ pgtype.UUID) (fakeRow, error) {
		return fakeRow{}, pgx.ErrNoRows
	}
	r := reqWithParam(t, "id", "11111111-1111-1111-1111-111111111111")
	_, apiErr := resolveByID(r, "id", fetch, "track")
	if apiErr == nil {
		t.Fatal("expected apiErr, got nil")
	}
	if apiErr.Status != 404 {
		t.Errorf("Status: got %d, want 404", apiErr.Status)
	}
	if apiErr.Code != "track_not_found" {
		t.Errorf("Code: got %q, want %q", apiErr.Code, "track_not_found")
	}
}

func TestResolveByID_Internal(t *testing.T) {
	cause := errors.New("boom")
	fetch := func(_ context.Context, _ pgtype.UUID) (fakeRow, error) {
		return fakeRow{}, cause
	}
	r := reqWithParam(t, "id", "11111111-1111-1111-1111-111111111111")
	_, apiErr := resolveByID(r, "id", fetch, "track")
	if apiErr == nil {
		t.Fatal("expected apiErr, got nil")
	}
	if apiErr.Status != 500 {
		t.Errorf("Status: got %d, want 500", apiErr.Status)
	}
	if !errors.Is(apiErr, cause) {
		t.Errorf("expected cause %v wrapped in apiErr; got %v", cause, apiErr)
	}
}

func TestResolveByID_Success(t *testing.T) {
	want := fakeRow{Name: "alpha"}
	fetch := func(_ context.Context, id pgtype.UUID) (fakeRow, error) {
		want.ID = id
		return want, nil
	}
	r := reqWithParam(t, "id", "11111111-1111-1111-1111-111111111111")
	got, apiErr := resolveByID(r, "id", fetch, "track")
	if apiErr != nil {
		t.Fatalf("unexpected apiErr: %v", apiErr)
	}
	if got.Name != want.Name {
		t.Errorf("Name: got %q, want %q", got.Name, want.Name)
	}
	if got.ID != want.ID {
		t.Errorf("ID: got %+v, want %+v", got.ID, want.ID)
	}
}
