package web

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

// v0.126.3 — the storage wizard pages must render the session's CSRF token into the meta tag
// (the wizard's fetch() POSTs /api/storage/init|attach with csrfHeaders()). The pre-fix
// storageWizardPageHandler used raw render() (no CSRF injection) → empty meta → every init
// POST on a CLAIMED box died with "token mismatch". Latent until the claim arc because an
// unclaimed box skips CsrfProtect entirely; first live hit was the agent-0.87.0 drill wizard
// leg (2026-07-13).
// COMPANION red-proof: swap executeTemplate back to render() → both cases fail on the empty
// meta token.
func TestStorageWizardPages_CarrySessionCSRFToken(t *testing.T) {
	s := testServer(t)
	s.loadTemplates()
	if s.sessions == nil {
		s.sessions = map[string]*session{} // testServer skips the login wiring
	}

	// A real session, exactly as login creates it.
	tok := s.createSession()
	want := s.csrfTokenForSession(tok)
	if want == "" {
		t.Fatal("test session has no csrf token")
	}

	for _, page := range []string{"storage_init", "storage_attach"} {
		rr := httptest.NewRecorder()
		req := httptest.NewRequest("GET", "/storage/init", nil)
		req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: tok})
		s.storageWizardPageHandler(rr, req, page)
		body := rr.Body.String()
		if !strings.Contains(body, `name="csrf-token" content="`+want+`"`) {
			t.Errorf("%s: the csrf meta must carry the SESSION token (got empty or wrong token)", page)
		}
	}
}
