package web

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

	"git.fabledsword.com/bvandeusen/minstrel/internal/config"
)

func TestHandler_ServesIndexAtRoot(t *testing.T) {
	req := httptest.NewRequest(http.MethodGet, "/", nil)
	rec := httptest.NewRecorder()
	Handler(config.BrandingConfig{}).ServeHTTP(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200", rec.Code)
	}
	if ct := rec.Header().Get("Content-Type"); !strings.Contains(ct, "text/html") {
		t.Errorf("Content-Type = %q, want text/html*", ct)
	}
	body, _ := io.ReadAll(rec.Body)
	if !strings.Contains(strings.ToLower(string(body)), "<html") {
		t.Errorf("body missing <html tag; got: %q", string(body))
	}
}

func TestHandler_UnknownPathFallsBackToIndex(t *testing.T) {
	req := httptest.NewRequest(http.MethodGet, "/artists/some-uuid", nil)
	rec := httptest.NewRecorder()
	Handler(config.BrandingConfig{}).ServeHTTP(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200 (SPA fallback)", rec.Code)
	}
	if ct := rec.Header().Get("Content-Type"); !strings.Contains(ct, "text/html") {
		t.Errorf("Content-Type = %q, want text/html* for SPA fallback", ct)
	}
}

func TestHandler_MissingAssetFallsBackToIndex(t *testing.T) {
	req := httptest.NewRequest(http.MethodGet, "/_app/immutable/chunks/does-not-exist.js", nil)
	rec := httptest.NewRecorder()
	Handler(config.BrandingConfig{}).ServeHTTP(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200 (fallback to index.html)", rec.Code)
	}
	if ct := rec.Header().Get("Content-Type"); !strings.Contains(ct, "text/html") {
		t.Errorf("Content-Type = %q, want text/html* for missing asset", ct)
	}
}
