package server
import (
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"sourcecraft.dev/bigbes/huntsman/internal/domain/search"
"sourcecraft.dev/bigbes/huntsman/internal/platform/health"
)
func newTestRouter(t *testing.T) http.Handler {
t.Helper()
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
svc, err := search.NewService("gh", "https://example.com")
if err != nil {
t.Fatalf("NewService: %v", err)
}
return Routes(logger, health.New(), search.NewHandler(svc))
}
func TestIndexHandler(t *testing.T) {
h := newTestRouter(t)
rr := httptest.NewRecorder()
h.ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), "GET", "/", http.NoBody))
if rr.Code != http.StatusOK {
t.Fatalf("status = %d", rr.Code)
}
if got := rr.Header().Get("Content-Type"); !strings.HasPrefix(got, "text/html") {
t.Errorf("content-type = %q", got)
}
body := rr.Body.String()
if !strings.Contains(body, `<link rel="search"`) {
t.Errorf("body missing OSD link tag: %q", body)
}
if !strings.Contains(body, "huntsman") {
t.Errorf("body missing service name")
}
}
func TestRoutesMountAllExpectedPaths(t *testing.T) {
h := newTestRouter(t)
cases := []struct {
path string
wantStatus int
}{
{"/healthz", 200},
{"/readyz", 200},
{"/", 200},
{"/providers", 200},
{"/opensearch.xml", 200},
{"/opensearch/gh.xml", 200},
{"/search?q=foo", 302},
}
for _, tc := range cases {
t.Run(tc.path, func(t *testing.T) {
rr := httptest.NewRecorder()
h.ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), "GET", tc.path, http.NoBody))
if rr.Code != tc.wantStatus {
t.Errorf("%s: status = %d, want %d", tc.path, rr.Code, tc.wantStatus)
}
})
}
}
func TestRoutesAttachRequestIDMiddleware(t *testing.T) {
h := newTestRouter(t)
rr := httptest.NewRecorder()
h.ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), "GET", "/", http.NoBody))
if rr.Header().Get("X-Request-ID") == "" {
t.Error("expected X-Request-ID header from middleware")
}
}
func TestRoutesUnknownPath404(t *testing.T) {
h := newTestRouter(t)
rr := httptest.NewRecorder()
h.ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), "GET", "/no-such-thing", http.NoBody))
if rr.Code != http.StatusNotFound {
t.Errorf("status = %d, want 404", rr.Code)
}
}