package admin_test

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

	"scrabble/gateway/internal/admin"
)

// newAdmin fronts a fake backend with the admin proxy. The fake backend records the
// path it receives so a test can assert the proxy forwards /_gm verbatim.
func newAdmin(t *testing.T) (front *httptest.Server, gotPath *string, cleanup func()) {
	t.Helper()
	var path string
	backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		path = r.URL.Path
		_, _ = w.Write([]byte("console"))
	}))
	proxy, err := admin.NewProxy(backend.URL, "ops", "secret", nil)
	if err != nil {
		t.Fatalf("new proxy: %v", err)
	}
	front = httptest.NewServer(proxy)
	return front, &path, func() { front.Close(); backend.Close() }
}

func TestAdminRejectsMissingCredentials(t *testing.T) {
	front, _, cleanup := newAdmin(t)
	defer cleanup()

	resp, err := http.Get(front.URL + "/_gm/")
	if err != nil {
		t.Fatal(err)
	}
	defer func() { _ = resp.Body.Close() }()
	if resp.StatusCode != http.StatusUnauthorized {
		t.Fatalf("status = %d, want 401", resp.StatusCode)
	}
	if resp.Header.Get("WWW-Authenticate") == "" {
		t.Error("missing WWW-Authenticate challenge")
	}
}

func TestAdminProxiesVerbatimWithCredentials(t *testing.T) {
	front, gotPath, cleanup := newAdmin(t)
	defer cleanup()

	req, _ := http.NewRequest(http.MethodGet, front.URL+"/_gm/complaints", nil)
	req.SetBasicAuth("ops", "secret")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		t.Fatal(err)
	}
	defer func() { _ = resp.Body.Close() }()
	body, _ := io.ReadAll(resp.Body)
	if resp.StatusCode != http.StatusOK || string(body) != "console" {
		t.Fatalf("status = %d body = %q, want 200 console", resp.StatusCode, body)
	}
	if *gotPath != "/_gm/complaints" {
		t.Errorf("backend path = %q, want /_gm/complaints (verbatim)", *gotPath)
	}
}

func TestAdminRejectsWrongPassword(t *testing.T) {
	front, _, cleanup := newAdmin(t)
	defer cleanup()

	req, _ := http.NewRequest(http.MethodGet, front.URL+"/_gm/", nil)
	req.SetBasicAuth("ops", "wrong")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		t.Fatal(err)
	}
	defer func() { _ = resp.Body.Close() }()
	if resp.StatusCode != http.StatusUnauthorized {
		t.Fatalf("status = %d, want 401", resp.StatusCode)
	}
}
