package app

import (
	"encoding/json"
	"io"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"

	"git.warky.dev/wdevs/amcs/internal/auth"
	"git.warky.dev/wdevs/amcs/internal/buildinfo"
	"git.warky.dev/wdevs/amcs/internal/config"
)

func TestStatusSnapshotHidesOAuthLinkWhenDisabled(t *testing.T) {
	tracker := auth.NewAccessTracker()
	snapshot := statusSnapshot(buildinfo.Info{Version: "v1.2.3", BuildDate: "2026-04-04", Commit: "abc123"}, tracker, false, time.Date(2026, 4, 4, 12, 0, 0, 0, time.UTC))

	if snapshot.OAuthEnabled {
		t.Fatal("OAuthEnabled = true, want false")
	}
	if snapshot.ConnectedCount != 0 {
		t.Fatalf("ConnectedCount = %d, want 0", snapshot.ConnectedCount)
	}
	if snapshot.Title == "" {
		t.Fatal("Title = empty, want non-empty")
	}
}

func TestStatusSnapshotShowsTrackedAccess(t *testing.T) {
	tracker := auth.NewAccessTracker()
	now := time.Date(2026, 4, 4, 12, 0, 0, 0, time.UTC)
	tracker.Record("client-a", "/files", "127.0.0.1:1234", "tester", "list_projects", now)

	snapshot := statusSnapshot(buildinfo.Info{Version: "v1.2.3"}, tracker, true, now)

	if !snapshot.OAuthEnabled {
		t.Fatal("OAuthEnabled = false, want true")
	}
	if snapshot.ConnectedCount != 1 {
		t.Fatalf("ConnectedCount = %d, want 1", snapshot.ConnectedCount)
	}
	if len(snapshot.Entries) != 0 {
		t.Fatalf("len(Entries) = %d, want 0 for counts-only status", len(snapshot.Entries))
	}
	if snapshot.Metrics.TotalRequests != 1 {
		t.Fatalf("Metrics.TotalRequests = %d, want 1", snapshot.Metrics.TotalRequests)
	}
	if snapshot.Metrics.UniqueIPs != 1 {
		t.Fatalf("Metrics.UniqueIPs = %d, want 1", snapshot.Metrics.UniqueIPs)
	}
	if snapshot.Metrics.UniqueAgents != 1 {
		t.Fatalf("Metrics.UniqueAgents = %d, want 1", snapshot.Metrics.UniqueAgents)
	}
	if snapshot.Metrics.UniqueTools != 1 {
		t.Fatalf("Metrics.UniqueTools = %d, want 1", snapshot.Metrics.UniqueTools)
	}
	if len(snapshot.Metrics.TopIPs) != 0 || len(snapshot.Metrics.TopAgents) != 0 || len(snapshot.Metrics.TopTools) != 0 {
		t.Fatalf("Top breakdowns should be hidden in counts-only status: %+v", snapshot.Metrics)
	}
}

func TestStatusAPIHandlerReturnsJSON(t *testing.T) {
	handler := statusAPIHandler(buildinfo.Info{Version: "v1"}, auth.NewAccessTracker(), true)
	req := httptest.NewRequest(http.MethodGet, "/api/status", nil)
	rec := httptest.NewRecorder()

	handler.ServeHTTP(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
	}
	if got := rec.Header().Get("Content-Type"); !strings.Contains(got, "application/json") {
		t.Fatalf("content-type = %q, want application/json", got)
	}

	var payload statusAPIResponse
	if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
		t.Fatalf("json.Unmarshal() error = %v", err)
	}
	if payload.Version != "v1" {
		t.Fatalf("version = %q, want %q", payload.Version, "v1")
	}
}

func TestStatusAPIHandlerRejectsStatusPath(t *testing.T) {
	handler := statusAPIHandler(buildinfo.Info{Version: "v1"}, auth.NewAccessTracker(), true)
	req := httptest.NewRequest(http.MethodGet, "/status", nil)
	rec := httptest.NewRecorder()

	handler.ServeHTTP(rec, req)

	if rec.Code != http.StatusNotFound {
		t.Fatalf("status = %d, want %d", rec.Code, http.StatusNotFound)
	}
}

func TestPublicStatusHandlerReturnsConnectedClientsOnly(t *testing.T) {
	tracker := auth.NewAccessTracker()
	now := time.Now().UTC()
	tracker.Record("recent-client", "/mcp", "127.0.0.1:1234", "tester", "list_projects", now.Add(-2*time.Minute))
	tracker.Record("stale-client", "/mcp", "127.0.0.1:9999", "tester", "list_projects", now.Add(-30*time.Minute))

	handler := publicStatusHandler(tracker)
	req := httptest.NewRequest(http.MethodGet, "/status", nil)
	rec := httptest.NewRecorder()

	handler.ServeHTTP(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
	}

	var payload publicStatusResponse
	if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
		t.Fatalf("json.Unmarshal() error = %v", err)
	}
	if payload.ConnectedCount != 1 {
		t.Fatalf("ConnectedCount = %d, want 1", payload.ConnectedCount)
	}
	if len(payload.Entries) != 1 {
		t.Fatalf("len(Entries) = %d, want 1", len(payload.Entries))
	}
	if payload.Entries[0].KeyID != "recent-client" {
		t.Fatalf("Entries[0].KeyID = %q, want %q", payload.Entries[0].KeyID, "recent-client")
	}
	if payload.Entries[0].LastAccessedAt.Before(now.Add(-11 * time.Minute)) {
		t.Fatalf("Entries[0].LastAccessedAt = %v, expected recent timestamp", payload.Entries[0].LastAccessedAt)
	}
}

func TestHomeHandlerAllowsHead(t *testing.T) {
	handler := homeHandler(buildinfo.Info{Version: "v1"}, auth.NewAccessTracker(), false)
	req := httptest.NewRequest(http.MethodHead, "/", nil)
	rec := httptest.NewRecorder()

	handler.ServeHTTP(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
	}
	if body := rec.Body.String(); body != "" {
		t.Fatalf("body = %q, want empty for HEAD", body)
	}
}

func TestHomeHandlerServesIndex(t *testing.T) {
	handler := homeHandler(buildinfo.Info{Version: "v1"}, auth.NewAccessTracker(), false)
	req := httptest.NewRequest(http.MethodGet, "/", nil)
	rec := httptest.NewRecorder()

	handler.ServeHTTP(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
	}
	if !strings.Contains(rec.Body.String(), "<div id=\"app\"></div>") {
		t.Fatalf("body = %q, want embedded UI index", rec.Body.String())
	}
}

func TestMiddlewareRecordsAuthenticatedAccess(t *testing.T) {
	keyring, err := auth.NewKeyring([]config.APIKey{{ID: "client-a", Value: "secret"}})
	if err != nil {
		t.Fatalf("NewKeyring() error = %v", err)
	}
	tracker := auth.NewAccessTracker()
	logger := slog.New(slog.NewTextHandler(io.Discard, nil))
	handler := auth.Middleware(config.AuthConfig{HeaderName: "x-brain-key"}, keyring, nil, nil, tracker, logger)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusNoContent)
	}))

	req := httptest.NewRequest(http.MethodGet, "/files", nil)
	req.Header.Set("x-brain-key", "secret")
	rec := httptest.NewRecorder()
	handler.ServeHTTP(rec, req)

	if rec.Code != http.StatusNoContent {
		t.Fatalf("status = %d, want %d", rec.Code, http.StatusNoContent)
	}
	snap := tracker.Snapshot()
	if len(snap) != 1 {
		t.Fatalf("len(snapshot) = %d, want 1", len(snap))
	}
	if snap[0].KeyID != "client-a" || snap[0].LastPath != "/files" {
		t.Fatalf("snapshot[0] = %+v, want keyID client-a and path /files", snap[0])
	}
}
