package web

// The empty-email wipe guard (Part 1, 2026-07-15 demo incident): saving notification prefs with a
// blank email box while events are still enabled must be REFUSED before it can store an empty email
// and push it to the hub (wiping the customer's provisioning-seeded alert address). Non-hollow: the
// guard is asserted by the REAL stored state (a temp-file Settings) — the email survives the refused
// save — plus the rendered Hungarian error and the repainted (overlaid) submission.

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

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

const guardErrSubstr = "bekapcsolt értesítésekhez szükséges" // distinctive slice of the exact Hungarian error

func notifyGuardServer(t *testing.T) (*Server, *settings.Settings) {
	t.Helper()
	lg := log.New(io.Discard, "", 0)
	dir := t.TempDir()
	cfg := &config.Config{}
	cfg.Customer.ID = "c1"
	cfg.Customer.Name = "Teszt"
	cfg.Customer.Domain = "example.hu"
	cfg.Paths.StacksDir = filepath.Join(dir, "stacks")
	cfg.Paths.DataDir = filepath.Join(dir, "data")
	cfg.Stacks.ComposeCommand = "docker compose"
	cfg.Web.SessionSecret = "test-session-secret-abcdef"
	cfg.Hub.Enabled = true // the notifications form (+ error/checkbox render) is gated on HubEnabled

	sett, err := settings.Load(filepath.Join(dir, "settings.json"), lg)
	if err != nil {
		t.Fatalf("settings: %v", err)
	}
	mgr, err := stacks.NewManager(cfg, lg)
	if err != nil {
		t.Fatalf("stacks: %v", err)
	}
	// notifier is left nil: the handler's sync path is guarded by `s.notifier != nil` — the guard
	// under test returns long before it anyway.
	s := &Server{cfg: cfg, settings: sett, stackMgr: mgr, logger: lg, version: "test"}
	s.loadTemplates()
	return s, sett
}

func postNotifications(t *testing.T, s *Server, form url.Values) *httptest.ResponseRecorder {
	t.Helper()
	req := httptest.NewRequest(http.MethodPost, "/settings/notifications", strings.NewReader(form.Encode()))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	rr := httptest.NewRecorder()
	s.settingsNotificationsHandler(rr, req)
	return rr
}

// Guard fires: empty email + >=1 enabled event → refused; stored email UNCHANGED (not wiped), the
// Hungarian error rendered, and the just-submitted (not the stored) events repainted.
// Red-proof: delete the guard block → the stored email becomes "" (the wipe) and this test fails.
func TestNotificationsGuard_RefusesEmptyEmailWithEvents(t *testing.T) {
	s, sett := notifyGuardServer(t)
	// Seed a provisioning-set email + a DIFFERENT event than we submit (so the repaint assertion
	// distinguishes the overlaid submission from the stored prefs).
	if err := sett.SetNotificationPrefs(&settings.NotificationPrefs{
		Email: "seed@felhom.eu", EnabledEvents: []string{"node_down"}, CooldownHours: 6,
	}); err != nil {
		t.Fatal(err)
	}

	rr := postNotifications(t, s, url.Values{
		"notification_email":  {""},
		"event_backup_failed": {"on"},
		"cooldown_hours":      {"6"},
	})

	// The wipe was prevented: stored email + events are untouched (SetNotificationPrefs not called).
	got := sett.GetNotificationPrefs()
	if got.Email != "seed@felhom.eu" {
		t.Fatalf("stored email = %q, want seed@felhom.eu — the guard must not wipe it", got.Email)
	}
	if len(got.EnabledEvents) != 1 || got.EnabledEvents[0] != "node_down" {
		t.Errorf("stored events = %v, want [node_down] unchanged", got.EnabledEvents)
	}
	body := rr.Body.String()
	if !strings.Contains(body, guardErrSubstr) {
		t.Errorf("response missing the Hungarian guard error (len=%d)", len(body))
	}
	// The overlay repaints the SUBMITTED intent: backup_failed checked, seeded node_down NOT.
	if !strings.Contains(body, `event_backup_failed" checked`) {
		t.Errorf("submitted event backup_failed not repainted as checked")
	}
	if strings.Contains(body, `event_node_down" checked`) {
		t.Errorf("stored node_down leaked into the re-render — overlay not applied")
	}
}

// Legitimate clear-all: empty email + ZERO events → the save proceeds and intentionally clears the
// email (the hub push of an empty address is correct there).
func TestNotificationsGuard_AllowsEmptyEmailZeroEvents(t *testing.T) {
	s, sett := notifyGuardServer(t)
	if err := sett.SetNotificationPrefs(&settings.NotificationPrefs{
		Email: "seed@felhom.eu", EnabledEvents: []string{"backup_failed"}, CooldownHours: 6,
	}); err != nil {
		t.Fatal(err)
	}

	rr := postNotifications(t, s, url.Values{
		"notification_email": {""},
		"cooldown_hours":     {"6"},
	}) // no event_* checkboxes

	// The save PROCEEDED (guard did not fire): the email is intentionally cleared. (Note:
	// GetNotificationPrefs re-defaults an empty EnabledEvents list on read, so the stored-empty
	// events are not asserted here — the email clear is the observable proof the save ran.)
	if p := sett.GetNotificationPrefs(); p.Email != "" {
		t.Errorf("email = %q, want cleared (legitimate turn-everything-off)", p.Email)
	}
	if strings.Contains(rr.Body.String(), guardErrSubstr) {
		t.Errorf("guard wrongly fired on a legitimate clear-all")
	}
}

// Normal save (regression guard): non-empty email + events persist unchanged.
func TestNotificationsGuard_NormalSavePersists(t *testing.T) {
	s, sett := notifyGuardServer(t)

	postNotifications(t, s, url.Values{
		"notification_email":  {"new@felhom.eu"},
		"event_backup_failed": {"on"},
		"cooldown_hours":      {"12"},
	})

	p := sett.GetNotificationPrefs()
	if p.Email != "new@felhom.eu" {
		t.Errorf("email = %q, want new@felhom.eu", p.Email)
	}
	if len(p.EnabledEvents) != 1 || p.EnabledEvents[0] != "backup_failed" {
		t.Errorf("events = %v, want [backup_failed]", p.EnabledEvents)
	}
	if p.CooldownHours != 12 {
		t.Errorf("cooldown = %d, want 12", p.CooldownHours)
	}
}
