package api

import (
	"bytes"
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"github.com/go-chi/chi/v5"

	"git.fabledsword.com/bvandeusen/minstrel/internal/auth"
	"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
	"git.fabledsword.com/bvandeusen/minstrel/internal/lidarr"
	"git.fabledsword.com/bvandeusen/minstrel/internal/lidarrconfig"
	"git.fabledsword.com/bvandeusen/minstrel/internal/lidarrrequests"
)

// newAdminRequestsRouter builds a test chi router with the three admin/requests
// endpoints. RequireAdmin middleware is applied. Tests inject a user into
// context directly (skipping RequireUser).
func newAdminRequestsRouter(h *handlers) chi.Router {
	r := chi.NewRouter()
	r.Route("/api/admin", func(admin chi.Router) {
		admin.Use(auth.RequireAdmin())
		admin.Get("/requests", h.handleListAdminRequests)
		admin.Post("/requests/{id}/approve", h.handleApproveRequest)
		admin.Post("/requests/{id}/reject", h.handleRejectRequest)
	})
	return r
}

// doAdminRequestReq fires an HTTP request at the admin requests router with
// the given user injected into context (bypassing RequireUser).
func doAdminRequestReq(t *testing.T, h *handlers, method, path string, body []byte, user dbq.User) *httptest.ResponseRecorder {
	t.Helper()
	var reqBody *bytes.Buffer
	if body != nil {
		reqBody = bytes.NewBuffer(body)
	} else {
		reqBody = bytes.NewBuffer(nil)
	}
	req := httptest.NewRequest(method, path, reqBody)
	if body != nil {
		req.Header.Set("Content-Type", "application/json")
	}
	req = withUser(req, user)
	w := httptest.NewRecorder()
	newAdminRequestsRouter(h).ServeHTTP(w, req)
	return w
}

// testHandlersWithClientFn creates a handlers instance with a real clientFn
// so Service.Approve actually calls Lidarr during tests.
func testHandlersWithClientFn(t *testing.T) (*handlers, *lidarrconfig.Service) {
	t.Helper()
	h, _ := testHandlers(t)
	lidarrCfg := lidarrconfig.New(h.pool)
	clientFn := func() *lidarr.Client {
		cfg, err := lidarrCfg.Get(context.Background())
		if err != nil || !cfg.Enabled || cfg.BaseURL == "" {
			return nil
		}
		return lidarr.NewClient(cfg.BaseURL, cfg.APIKey)
	}
	h.lidarrRequests = lidarrrequests.NewService(h.pool, lidarrCfg, clientFn, nil)
	return h, lidarrCfg
}

// seedPendingArtistRequest creates a pending artist-kind lidarr request row
// for the given user and returns its parsed requestView.
func seedPendingArtistRequest(t *testing.T, h *handlers, user dbq.User, artistMBID, artistName string) requestView {
	t.Helper()
	return createArtistRequest(t, h, user, artistMBID, artistName)
}

// TestHandleListAdminRequests_DefaultStatus_Pending seeds 2 pending + 1 rejected
// and verifies that GET without ?status returns only the 2 pending rows.
func TestHandleListAdminRequests_DefaultStatus_Pending(t *testing.T) {
	h, _ := testHandlersWithClientFn(t)
	resetLidarrState(t, h)

	alice := seedUser(t, h.pool, "alice", "pw", false)
	admin := seedUser(t, h.pool, "admin", "pw", true)

	createArtistRequest(t, h, alice, "mbid-pending-1", "Pending Artist 1")
	createArtistRequest(t, h, alice, "mbid-pending-2", "Pending Artist 2")

	// Reject one request directly via service.
	rv3 := createArtistRequest(t, h, alice, "mbid-reject-1", "Reject Me")
	_, err := h.lidarrRequests.Reject(context.Background(), rv3.ID, admin.ID, "test")
	if err != nil {
		t.Fatalf("reject seed: %v", err)
	}

	w := doAdminRequestReq(t, h, http.MethodGet, "/api/admin/requests", nil, admin)
	if w.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String())
	}

	var results []requestView
	if err := json.Unmarshal(w.Body.Bytes(), &results); err != nil {
		t.Fatalf("decode: %v; body = %s", err, w.Body.String())
	}
	if len(results) != 2 {
		t.Fatalf("len(results) = %d, want 2 (pending only)", len(results))
	}
	for _, rv := range results {
		if rv.Status != "pending" {
			t.Errorf("result status = %q, want pending", rv.Status)
		}
	}
}

// TestHandleListAdminRequests_StatusFilter verifies GET ?status=rejected returns
// only rejected rows.
func TestHandleListAdminRequests_StatusFilter(t *testing.T) {
	h, _ := testHandlersWithClientFn(t)
	resetLidarrState(t, h)

	alice := seedUser(t, h.pool, "alice", "pw", false)
	admin := seedUser(t, h.pool, "admin", "pw", true)

	createArtistRequest(t, h, alice, "mbid-pending-f1", "Pending Filter 1")

	rv2 := createArtistRequest(t, h, alice, "mbid-rejected-f1", "Rejected Filter 1")
	_, err := h.lidarrRequests.Reject(context.Background(), rv2.ID, admin.ID, "")
	if err != nil {
		t.Fatalf("reject seed: %v", err)
	}

	w := doAdminRequestReq(t, h, http.MethodGet, "/api/admin/requests?status=rejected", nil, admin)
	if w.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String())
	}

	var results []requestView
	if err := json.Unmarshal(w.Body.Bytes(), &results); err != nil {
		t.Fatalf("decode: %v; body = %s", err, w.Body.String())
	}
	if len(results) != 1 {
		t.Fatalf("len(results) = %d, want 1 rejected row", len(results))
	}
	if results[0].Status != "rejected" {
		t.Errorf("status = %q, want rejected", results[0].Status)
	}
}

// TestHandleListAdminRequests_BadStatus_400 verifies GET with an invalid
// ?status returns 400.
func TestHandleListAdminRequests_BadStatus_400(t *testing.T) {
	h, _ := testHandlersWithClientFn(t)
	resetLidarrState(t, h)

	admin := seedUser(t, h.pool, "admin", "pw", true)

	w := doAdminRequestReq(t, h, http.MethodGet, "/api/admin/requests?status=garbage", nil, admin)
	if w.Code != http.StatusBadRequest {
		t.Fatalf("status = %d, want 400; body = %s", w.Code, w.Body.String())
	}
	var resp map[string]string
	if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
		t.Fatalf("decode: %v; body = %s", err, w.Body.String())
	}
	if resp["error"] != "invalid_status" {
		t.Errorf("error = %q, want invalid_status", resp["error"])
	}
}

// TestHandleApproveRequest_HappyPath seeds a Lidarr stub, seeds a pending
// artist request, and verifies POST /approve → 200 with row status=approved.
func TestHandleApproveRequest_HappyPath(t *testing.T) {
	h, _ := testHandlersWithClientFn(t)
	resetLidarrState(t, h)

	stub := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		switch {
		case strings.Contains(r.URL.Path, "/metadataprofile"):
			_, _ = w.Write([]byte(`[{"id":1,"name":"Standard"}]`))
		case strings.Contains(r.URL.Path, "/qualityprofile"):
			_, _ = w.Write([]byte(`[{"id":1,"name":"Lossless"}]`))
		default:
			_, _ = w.Write([]byte(`{"id":1}`))
		}
	}))
	t.Cleanup(stub.Close)

	saveLidarrConfig(t, h, stub.URL, true)

	alice := seedUser(t, h.pool, "alice", "pw", false)
	admin := seedUser(t, h.pool, "admin", "pw", true)

	rv := seedPendingArtistRequest(t, h, alice, "artist-mbid-approve", "Approve Me")

	w := doAdminRequestReq(t, h, http.MethodPost, "/api/admin/requests/"+uuidToString(rv.ID)+"/approve", nil, admin)
	if w.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String())
	}

	var got requestView
	if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
		t.Fatalf("decode: %v; body = %s", err, w.Body.String())
	}
	if got.Status != "approved" {
		t.Errorf("status = %q, want approved", got.Status)
	}
	if got.ID != rv.ID {
		t.Errorf("id mismatch")
	}
}

// TestHandleApproveRequest_OverrideUsed seeds config with default qp=1/root="/m",
// approves with override qp=5/root="/other", verifies the stub received those
// values and the row reflects the overrides.
func TestHandleApproveRequest_OverrideUsed(t *testing.T) {
	h, _ := testHandlersWithClientFn(t)
	resetLidarrState(t, h)

	var capturedBody []byte
	stub := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method == http.MethodPost {
			buf := make([]byte, 4096)
			n, _ := r.Body.Read(buf)
			capturedBody = buf[:n]
		}
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		switch {
		case strings.Contains(r.URL.Path, "/metadataprofile"):
			_, _ = w.Write([]byte(`[{"id":1,"name":"Standard"}]`))
		case strings.Contains(r.URL.Path, "/qualityprofile"):
			_, _ = w.Write([]byte(`[{"id":1,"name":"Lossless"}]`))
		default:
			_, _ = w.Write([]byte(`{"id":1}`))
		}
	}))
	t.Cleanup(stub.Close)

	// Save config with default qp=1, root="/m".
	if err := lidarrconfig.New(h.pool).Save(context.Background(), lidarrconfig.Config{
		Enabled:                 true,
		BaseURL:                 stub.URL,
		APIKey:                  "test-key",
		DefaultQualityProfileID: 1,
		DefaultRootFolderPath:   "/m",
	}); err != nil {
		t.Fatalf("save config: %v", err)
	}

	alice := seedUser(t, h.pool, "alice", "pw", false)
	admin := seedUser(t, h.pool, "admin", "pw", true)

	rv := seedPendingArtistRequest(t, h, alice, "artist-mbid-override", "Override Me")

	body := []byte(`{"quality_profile_id":5,"root_folder_path":"/other"}`)
	w := doAdminRequestReq(t, h, http.MethodPost, "/api/admin/requests/"+uuidToString(rv.ID)+"/approve", body, admin)
	if w.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String())
	}

	// Verify stub received the override values.
	var stubPayload map[string]any
	if err := json.Unmarshal(capturedBody, &stubPayload); err != nil {
		t.Fatalf("decode stub payload: %v; body = %s", err, capturedBody)
	}
	if qp, _ := stubPayload["qualityProfileId"].(float64); int(qp) != 5 {
		t.Errorf("stub qualityProfileId = %v, want 5", stubPayload["qualityProfileId"])
	}
	if rf, _ := stubPayload["rootFolderPath"].(string); rf != "/other" {
		t.Errorf("stub rootFolderPath = %q, want /other", rf)
	}

	// Verify the returned row reflects the overrides.
	var got requestView
	if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
		t.Fatalf("decode response: %v; body = %s", err, w.Body.String())
	}
	if got.QualityProfileID == nil || *got.QualityProfileID != 5 {
		t.Errorf("quality_profile_id = %v, want 5", got.QualityProfileID)
	}
	if got.RootFolderPath == nil || *got.RootFolderPath != "/other" {
		t.Errorf("root_folder_path = %v, want /other", got.RootFolderPath)
	}
}

// TestHandleApproveRequest_LidarrUnreachable_ApprovesDeferred points config
// at an unreachable port and verifies the durable-approve contract: POST
// /approve still succeeds (200) and the request becomes approved with the
// Lidarr add deferred (lidarr_add_confirmed_at NULL) for the reconciler to
// retry — the admin's decision is never lost to a transient Lidarr outage.
func TestHandleApproveRequest_LidarrUnreachable_ApprovesDeferred(t *testing.T) {
	h, _ := testHandlersWithClientFn(t)
	resetLidarrState(t, h)

	saveLidarrConfig(t, h, "http://127.0.0.1:1", true)

	alice := seedUser(t, h.pool, "alice", "pw", false)
	admin := seedUser(t, h.pool, "admin", "pw", true)

	rv := seedPendingArtistRequest(t, h, alice, "artist-mbid-unreachable", "Unreachable")

	w := doAdminRequestReq(t, h, http.MethodPost, "/api/admin/requests/"+uuidToString(rv.ID)+"/approve", nil, admin)
	if w.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200 (durable approve despite Lidarr down); body = %s", w.Code, w.Body.String())
	}

	// Must no longer be pending.
	pending, err := h.lidarrRequests.ListByStatus(context.Background(), "pending", 10)
	if err != nil {
		t.Fatalf("list pending: %v", err)
	}
	for _, r := range pending {
		if r.ID == rv.ID {
			t.Error("row still pending after durable approve")
		}
	}

	// Must be approved with the add deferred (confirmed_at NULL) so the
	// reconciler retries it — not failed, not lost.
	approved, err := h.lidarrRequests.ListByStatus(context.Background(), "approved", 10)
	if err != nil {
		t.Fatalf("list approved: %v", err)
	}
	var got *dbq.LidarrRequest
	for i := range approved {
		if approved[i].ID == rv.ID {
			got = &approved[i]
			break
		}
	}
	if got == nil {
		t.Fatalf("row %s not in approved after approve with Lidarr down", uuidToString(rv.ID))
	}
	if got.LidarrAddConfirmedAt.Valid {
		t.Error("lidarr_add_confirmed_at set despite Lidarr unreachable; want NULL (deferred to reconciler)")
	}
}

// TestHandleApproveRequest_NotPending_409 pre-rejects a row and verifies
// POST /approve → 409 request_not_pending.
func TestHandleApproveRequest_NotPending_409(t *testing.T) {
	h, _ := testHandlersWithClientFn(t)
	resetLidarrState(t, h)

	// Need an enabled Lidarr config so Approve reaches the not-pending check.
	stub := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusOK)
		_, _ = w.Write([]byte(`{"id":1}`))
	}))
	t.Cleanup(stub.Close)
	saveLidarrConfig(t, h, stub.URL, true)

	alice := seedUser(t, h.pool, "alice", "pw", false)
	admin := seedUser(t, h.pool, "admin", "pw", true)

	rv := seedPendingArtistRequest(t, h, alice, "artist-mbid-notpending", "Not Pending")

	// Pre-reject the row.
	_, err := h.lidarrRequests.Reject(context.Background(), rv.ID, admin.ID, "pre-rejected")
	if err != nil {
		t.Fatalf("pre-reject: %v", err)
	}

	w := doAdminRequestReq(t, h, http.MethodPost, "/api/admin/requests/"+uuidToString(rv.ID)+"/approve", nil, admin)
	if w.Code != http.StatusConflict {
		t.Fatalf("status = %d, want 409; body = %s", w.Code, w.Body.String())
	}
	var resp map[string]string
	if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
		t.Fatalf("decode: %v; body = %s", err, w.Body.String())
	}
	if resp["error"] != "request_not_pending" {
		t.Errorf("error = %q, want request_not_pending", resp["error"])
	}
}

// TestHandleRejectRequest_HappyPath verifies POST /reject with notes returns
// 200 and the row transitions to rejected with notes saved.
func TestHandleRejectRequest_HappyPath(t *testing.T) {
	h, _ := testHandlersWithClientFn(t)
	resetLidarrState(t, h)

	alice := seedUser(t, h.pool, "alice", "pw", false)
	admin := seedUser(t, h.pool, "admin", "pw", true)

	rv := seedPendingArtistRequest(t, h, alice, "artist-mbid-reject", "Reject Me")

	body := []byte(`{"notes":"low-quality release; will look for the remaster"}`)
	w := doAdminRequestReq(t, h, http.MethodPost, "/api/admin/requests/"+uuidToString(rv.ID)+"/reject", body, admin)
	if w.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String())
	}

	var got requestView
	if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
		t.Fatalf("decode: %v; body = %s", err, w.Body.String())
	}
	if got.Status != "rejected" {
		t.Errorf("status = %q, want rejected", got.Status)
	}
	if got.Notes == nil || *got.Notes != "low-quality release; will look for the remaster" {
		t.Errorf("notes = %v, want expected string", got.Notes)
	}
}

// TestHandleRejectRequest_NoNotes_OK verifies POST /reject with empty body
// returns 200 (notes are optional).
func TestHandleRejectRequest_NoNotes_OK(t *testing.T) {
	h, _ := testHandlersWithClientFn(t)
	resetLidarrState(t, h)

	alice := seedUser(t, h.pool, "alice", "pw", false)
	admin := seedUser(t, h.pool, "admin", "pw", true)

	rv := seedPendingArtistRequest(t, h, alice, "artist-mbid-reject-nonotes", "Reject No Notes")

	w := doAdminRequestReq(t, h, http.MethodPost, "/api/admin/requests/"+uuidToString(rv.ID)+"/reject", nil, admin)
	if w.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String())
	}

	var got requestView
	if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
		t.Fatalf("decode: %v; body = %s", err, w.Body.String())
	}
	if got.Status != "rejected" {
		t.Errorf("status = %q, want rejected", got.Status)
	}
}

// TestAdminRequestsEndpoints_NonAdmin403 is a table-driven test verifying that
// all 3 admin request endpoints reject non-admin users with 403.
func TestAdminRequestsEndpoints_NonAdmin403(t *testing.T) {
	h, _ := testHandlersWithClientFn(t)
	resetLidarrState(t, h)

	nonAdmin := seedUser(t, h.pool, "regular", "pw", false)

	// Use a placeholder UUID for the ID endpoints.
	fakeID := "00000000-0000-0000-0000-000000000001"

	cases := []struct {
		method string
		path   string
		body   []byte
	}{
		{http.MethodGet, "/api/admin/requests", nil},
		{http.MethodPost, "/api/admin/requests/" + fakeID + "/approve", nil},
		{http.MethodPost, "/api/admin/requests/" + fakeID + "/reject", nil},
	}

	for _, tc := range cases {
		tc := tc
		t.Run(tc.method+" "+tc.path, func(t *testing.T) {
			w := doAdminRequestReq(t, h, tc.method, tc.path, tc.body, nonAdmin)
			if w.Code != http.StatusForbidden {
				t.Fatalf("status = %d, want 403; body = %s", w.Code, w.Body.String())
			}
			var resp map[string]string
			if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
				t.Fatalf("decode: %v; body = %s", err, w.Body.String())
			}
			if resp["error"] != "not_authorized" {
				t.Errorf("error = %q, want not_authorized", resp["error"])
			}
		})
	}
}
