package httpx

import (
	"net/http"
	"net/http/httptest"
	"testing"
)

func okHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusOK)
		_, _ = w.Write([]byte("metric_x 1\n"))
	})
}

func TestMetricsNotMountedWhenNil(t *testing.T) {
	r := NewRouter(RouterDeps{})
	req := httptest.NewRequest("GET", "/metrics", nil)
	rec := httptest.NewRecorder()
	r.ServeHTTP(rec, req)
	// No /metrics route and no SPA fallback -> 404.
	if rec.Code != http.StatusNotFound {
		t.Fatalf("status = %d, want 404 (no metrics handler)", rec.Code)
	}
}

func TestMetricsOpenWhenNoToken(t *testing.T) {
	r := NewRouter(RouterDeps{MetricsHandler: okHandler()})
	req := httptest.NewRequest("GET", "/metrics", nil)
	rec := httptest.NewRecorder()
	r.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200", rec.Code)
	}
}

func TestMetricsTokenGated(t *testing.T) {
	r := NewRouter(RouterDeps{MetricsHandler: okHandler(), MetricsAuthToken: "secret"})

	// no token -> 401
	rec := httptest.NewRecorder()
	r.ServeHTTP(rec, httptest.NewRequest("GET", "/metrics", nil))
	if rec.Code != http.StatusUnauthorized {
		t.Fatalf("no-token status = %d, want 401", rec.Code)
	}

	// wrong token -> 401
	rec = httptest.NewRecorder()
	req := httptest.NewRequest("GET", "/metrics", nil)
	req.Header.Set("Authorization", "Bearer nope")
	r.ServeHTTP(rec, req)
	if rec.Code != http.StatusUnauthorized {
		t.Fatalf("wrong-token status = %d, want 401", rec.Code)
	}

	// correct bearer -> 200
	rec = httptest.NewRecorder()
	req = httptest.NewRequest("GET", "/metrics", nil)
	req.Header.Set("Authorization", "Bearer secret")
	r.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("bearer status = %d, want 200", rec.Code)
	}

	// correct query token -> 200
	rec = httptest.NewRecorder()
	r.ServeHTTP(rec, httptest.NewRequest("GET", "/metrics?token=secret", nil))
	if rec.Code != http.StatusOK {
		t.Fatalf("query-token status = %d, want 200", rec.Code)
	}
}
