package webui

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

	"mailgoserver/internal/config"
)

// TestSettingsUpdateSavesUppercaseDefinedKeys guards against a regression where
// settingsUpdate compared the submitted form field against the ini key's exact
// stored case (e.g. "SMTP_PORT", as the defaults table defines it) instead of the
// lowercase name settings.html always submits — silently dropping every edit to a
// key whose default name isn't already lowercase.
func TestSettingsUpdateSavesUppercaseDefinedKeys(t *testing.T) {
	app := newTestApp(t)

	// Swap in a config produced the real way (config.Load + defaults), where keys
	// like SMTP_PORT keep their defined uppercase name — unlike newTestApp's own
	// hand-built, already-lowercase fixture cfg.
	dir := t.TempDir()
	configPath := filepath.Join(dir, "settings.ini")
	realCfg, err := config.Load(configPath)
	if err != nil {
		t.Fatal(err)
	}
	app.Cfg = realCfg
	app.ConfigPath = configPath

	mux := app.Mux()
	cookie := loginSession(t, app)

	form := url.Values{"Server.smtp_port": {"2525"}}
	req := httptest.NewRequest(http.MethodPost, "/pymta-manager/settings_update", strings.NewReader(form.Encode()))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.AddCookie(cookie)
	rec := httptest.NewRecorder()
	mux.ServeHTTP(rec, req)

	if rec.Code != http.StatusFound {
		t.Fatalf("settings_update: status=%d body=%s", rec.Code, rec.Body.String())
	}
	got := app.Cfg.Section("Server").Key("SMTP_PORT").Value()
	if got != "2525" {
		t.Fatalf("SMTP_PORT not updated: got %q, want %q", got, "2525")
	}
}
