package app

import (
	"strings"
	"testing"

	"github.com/correx/tui-go/internal/protocol"
)

func configModel() Model {
	m := NewModel(nil)
	m.width, m.height = 120, 40
	m.theme = NewTheme(SoftBlue)
	m.overlay = OverlayConfig
	m.configFields = []protocol.ConfigFieldDto{
		{Key: "project.enabled", Type: "BOOL", Value: "false"},
		{Key: "tui.theme", Type: "ENUM", Value: "dark", Options: []string{"dark", "light", "soft-blue"}},
		{Key: "router.generation.max_tokens", Type: "INT", Value: "512"},
	}
	return m
}

func TestConfigToggleBoolStagesFlippedValue(t *testing.T) {
	m := configModel()
	updated, _ := m.handleConfigKey(keyMsg{Type: keyEnter})
	m = updated.(Model)
	if m.configStaged["project.enabled"] != "true" {
		t.Fatalf("want staged project.enabled=true, got %q", m.configStaged["project.enabled"])
	}
	out := m.configModal()
	if !strings.Contains(out, "project.enabled") {
		t.Fatalf("modal missing field key:\n%s", out)
	}
	if !strings.Contains(out, "*true") {
		t.Fatalf("modal missing staged marker for flipped value:\n%s", out)
	}
}

func TestConfigEnumCycles(t *testing.T) {
	m := configModel()
	m.configIndex = 1 // tui.theme
	updated, _ := m.handleConfigKey(keyMsg{Type: keyEnter})
	m = updated.(Model)
	if m.configStaged["tui.theme"] != "light" {
		t.Fatalf("want staged tui.theme=light (next after dark), got %q", m.configStaged["tui.theme"])
	}
}

func TestConfigIntEditCommitsBuffer(t *testing.T) {
	m := configModel()
	m.configIndex = 2 // router.generation.max_tokens
	// Enter edit mode.
	updated, _ := m.handleConfigKey(keyMsg{Type: keyEnter})
	m = updated.(Model)
	if !m.configEditing {
		t.Fatalf("expected edit mode after enter on INT field")
	}
	// Clear the seeded buffer and type a new value.
	m.configEditBuf = ""
	for _, r := range "1024" {
		updated, _ = m.handleConfigKey(keyMsg{Type: keyRunes, Runes: []rune{r}})
		m = updated.(Model)
	}
	updated, _ = m.handleConfigKey(keyMsg{Type: keyEnter})
	m = updated.(Model)
	if m.configEditing {
		t.Fatalf("expected edit mode to end after commit")
	}
	if m.configStaged["router.generation.max_tokens"] != "1024" {
		t.Fatalf("want staged max_tokens=1024, got %q", m.configStaged["router.generation.max_tokens"])
	}
}

func TestConfigSnapshotClearsStagedOnCleanReply(t *testing.T) {
	m := configModel()
	m.configStaged["project.enabled"] = "true"
	m.applyServer(protocol.ServerMessage{
		Type:         protocol.TypeConfigSnapshot,
		ConfigFields: []protocol.ConfigFieldDto{{Key: "project.enabled", Type: "BOOL", Value: "true"}},
	})
	if len(m.configStaged) != 0 {
		t.Fatalf("expected staged edits cleared on clean snapshot, got %v", m.configStaged)
	}
}
