package web

// v0.48.0 parts 3+4a — scoped auto-refresh (Group C: structural pins; live behavior is validated
// in the browser per the task's §13) and the style.css cache-bust rider (Group D).

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

	"gitea.dooplex.hu/admin/felhom-hub/internal/store"
)

// Group C — the refresh machinery's server-rendered structure: the live-tab list is DATA on the
// nav, the script consumes that attribute (not a hardcoded copy), a delegated dirty listener
// exists, and the legacy #tab=settings hash still lands on the Edit tab.
func TestCustomerRefresh_ScopedStructure(t *testing.T) {
	s, st := newTestServer(t)
	if err := st.SaveCustomerConfig(&store.CustomerConfig{
		CustomerID: "c1", CustomerName: "Acme", Domain: "acme.hu",
		RetrievalPassword: "pw", APIKey: "k", Status: "active",
	}); err != nil {
		t.Fatal(err)
	}
	// The toggle + refresh script render only with reports.
	if err := st.SaveReport("c1", []byte(tabsTestReportJSON)); err != nil {
		t.Fatal(err)
	}
	html := renderCustomerPage(t, s, "c1")

	// The nav carries the live-tab set (edit/setup/backup/notifications are deliberately absent).
	if !strings.Contains(html, `data-live-tabs="overview,applications,events,host"`) {
		t.Error("tab nav missing the data-live-tabs attribute")
	}
	// The script READS the attribute — the literal appears beyond the nav markup itself.
	if !strings.Contains(html, `getAttribute('data-live-tabs')`) {
		t.Error("refresh script does not read data-live-tabs (hardcoded live set?)")
	}
	// Delegated dirty listener: any input anywhere pauses the reload.
	if !strings.Contains(html, `document.addEventListener('input', markDirty)`) ||
		!strings.Contains(html, `document.addEventListener('change', markDirty)`) {
		t.Error("delegated input/change dirty listeners missing")
	}
	// Legacy hash alias: #tab=settings activates the Edit tab — in the tabs script AND the
	// refresh script's live-tab resolution.
	if got := strings.Count(html, `if (t === 'settings') t = 'edit';`); got != 2 {
		t.Errorf("settings→edit alias count = %d, want 2 (tabs script + refresh script)", got)
	}
	// The (paused) hint element next to the toggle.
	if !strings.Contains(html, `id="refresh-paused-hint"`) {
		t.Error("(paused) hint element missing")
	}
	// The cadence, key, and toggle survived the rework.
	for _, want := range []string{"60000", "hub_auto_refresh", `id="autoRefreshToggle"`} {
		if !strings.Contains(html, want) {
			t.Errorf("refresh machinery missing %q", want)
		}
	}
}

// Group D — every rendered page's stylesheet link carries the version cache-bust (the v0.47.0
// gotcha: /style.css is served with max-age=3600, so an unversioned link shows stale styling for
// up to an hour after a deploy). RED-PROOF: reverting one template's link to a bare
// href="/style.css" fails that page's negative assertion.
func TestTemplates_StyleCSSCacheBust(t *testing.T) {
	s, st := newTestServer(t) // version = "test" → the link must be /style.css?v=test
	if err := st.SaveCustomerConfig(&store.CustomerConfig{
		CustomerID: "c1", CustomerName: "Acme", Domain: "acme.hu",
		RetrievalPassword: "pw", APIKey: "k", Status: "active",
	}); err != nil {
		t.Fatal(err)
	}
	if err := st.UpsertHost(&store.Host{HostID: "h1", CustomerID: "c1", APIKey: "hk"}); err != nil {
		t.Fatal(err)
	}

	pages := map[string]func() string{
		"dashboard": func() string {
			rr := httptest.NewRecorder()
			s.handleDashboard(rr, httptest.NewRequest("GET", "/", nil))
			return rr.Body.String()
		},
		"customer": func() string { return renderCustomerPage(t, s, "c1") },
		"host detail": func() string {
			rr := httptest.NewRecorder()
			s.handleHostDetail(rr, httptest.NewRequest("GET", "/hosts/h1", nil), "h1")
			return rr.Body.String()
		},
		"offsite": func() string {
			rr := httptest.NewRecorder()
			s.handleOffsite(rr, httptest.NewRequest("GET", "/offsite", nil))
			return rr.Body.String()
		},
		"customers list": func() string {
			rr := httptest.NewRecorder()
			s.handleConfigList(rr, httptest.NewRequest("GET", "/configs", nil))
			return rr.Body.String()
		},
		"config form (standalone)": func() string {
			rr := httptest.NewRecorder()
			s.handleConfigNewForm(rr, httptest.NewRequest("GET", "/configs/new", nil))
			return rr.Body.String()
		},
	}
	for name, render := range pages {
		html := render()
		if !strings.Contains(html, `href="/style.css?v=test"`) {
			t.Errorf("%s: stylesheet link missing the ?v={{hubVersion}} cache-bust", name)
		}
		if strings.Contains(html, `href="/style.css"`) {
			t.Errorf("%s: bare /style.css link remains", name)
		}
	}
}
