package middleware

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

func TestDashboardAuthSetsWWWAuthenticateHeader(t *testing.T) {
	handler := DashboardAuth("secret")(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	}))

	req := httptest.NewRequest(http.MethodGet, "/dashboard", nil)
	rr := httptest.NewRecorder()
	handler.ServeHTTP(rr, req)

	if got := rr.Header().Get("WWW-Authenticate"); got != `Basic realm="Claude Code Proxy"` {
		t.Fatalf("expected basic auth challenge header, got %q", got)
	}
}

func TestDashboardAuthRejectsWrongUsername(t *testing.T) {
	called := false
	handler := DashboardAuth("secret")(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		called = true
		w.WriteHeader(http.StatusOK)
	}))

	req := httptest.NewRequest(http.MethodGet, "/dashboard", nil)
	req.SetBasicAuth("not-admin", "secret")
	rr := httptest.NewRecorder()
	handler.ServeHTTP(rr, req)

	if called {
		t.Fatal("expected handler not to be called with wrong username")
	}
	if rr.Code != http.StatusUnauthorized {
		t.Fatalf("expected 401, got %d", rr.Code)
	}
}
