package handler

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

func TestBasicAuthMiddleware(t *testing.T) {
	cfg := BasicAuthConfig{
		Username: "admin",
		Password: "secret",
		Realm:    "AutoHero Admin",
	}
	protected := BasicAuthMiddleware(cfg)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	}))

	tests := []struct {
		name       string
		username   string
		password   string
		setAuth    bool
		wantStatus int
		wantHeader bool
	}{
		{
			name:       "missing credentials",
			setAuth:    false,
			wantStatus: http.StatusUnauthorized,
			wantHeader: true,
		},
		{
			name:       "invalid credentials",
			username:   "admin",
			password:   "wrong",
			setAuth:    true,
			wantStatus: http.StatusUnauthorized,
			wantHeader: true,
		},
		{
			name:       "valid credentials",
			username:   "admin",
			password:   "secret",
			setAuth:    true,
			wantStatus: http.StatusOK,
			wantHeader: false,
		},
	}

	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			req := httptest.NewRequest(http.MethodGet, "/admin/info", nil)
			if tc.setAuth {
				req.SetBasicAuth(tc.username, tc.password)
			}

			rr := httptest.NewRecorder()
			protected.ServeHTTP(rr, req)

			if rr.Code != tc.wantStatus {
				t.Fatalf("status = %d, want %d", rr.Code, tc.wantStatus)
			}
			gotHeader := rr.Header().Get("WWW-Authenticate") != ""
			if gotHeader != tc.wantHeader {
				t.Fatalf("WWW-Authenticate present = %v, want %v", gotHeader, tc.wantHeader)
			}
		})
	}
}

func TestBasicAuthMiddleware_DenyWhenNotConfigured(t *testing.T) {
	protected := BasicAuthMiddleware(BasicAuthConfig{})(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	}))

	req := httptest.NewRequest(http.MethodGet, "/admin/info", nil)
	req.SetBasicAuth("admin", "secret")
	rr := httptest.NewRecorder()
	protected.ServeHTTP(rr, req)

	if rr.Code != http.StatusUnauthorized {
		t.Fatalf("status = %d, want %d", rr.Code, http.StatusUnauthorized)
	}
	if rr.Header().Get("WWW-Authenticate") == "" {
		t.Fatal("expected WWW-Authenticate header")
	}
}
