package setup

import (
	"bytes"
	"io"
	"log"
	"net/http/httptest"
	"path/filepath"
	"strings"
	"testing"

	"gitea.dooplex.hu/admin/felhom-controller/internal/config"
	"gitea.dooplex.hu/admin/felhom-controller/internal/web"
)

// TestSetupCSSServesEmbedded (Scenario E, TASK-D0): the setup wizard must serve
// the web package's EMBEDDED stylesheet. The pre-fix handleCSS read a filesystem
// path derived from dataDir, which does not exist inside the container image, so
// production setup mode silently served the minimalCSS fallback.
func TestSetupCSSServesEmbedded(t *testing.T) {
	// dataDir whose derived legacy path (internal/web/templates/style.css
	// relative to its grandparent) cannot exist.
	dataDir := filepath.Join(t.TempDir(), "nonexistent-nested", "data")
	logger := log.New(io.Discard, "", 0)
	s := NewServer(&config.Config{}, dataDir, logger, "test")

	rec := httptest.NewRecorder()
	req := httptest.NewRequest("GET", "/static/style.css", nil)
	s.Handler().ServeHTTP(rec, req)

	if rec.Code != 200 {
		t.Fatalf("status = %d, want 200", rec.Code)
	}
	body := rec.Body.Bytes()
	if len(body) <= 10000 {
		t.Fatalf("body length = %d, want > 10000 (minimalCSS fallback served?)", len(body))
	}
	if !strings.Contains(string(body), "--bg-0: #0A1220") {
		t.Error("served CSS is missing the v2 token block (--bg-0)")
	}
	embedded, err := web.StyleCSS()
	if err != nil {
		t.Fatalf("web.StyleCSS() error: %v", err)
	}
	if !bytes.Equal(body, embedded) {
		t.Error("served CSS differs from the embedded web stylesheet")
	}
	if strings.Contains(string(body), ".setup-container") {
		t.Error("minimalCSS fallback was served instead of the embedded stylesheet")
	}
}
