package tui

import (
	"strings"
	"testing"

	tea "github.com/charmbracelet/bubbletea"

	"incredigo/internal/discover"
	"incredigo/internal/worklist"
)

func key(s string) tea.KeyMsg {
	switch s {
	case "enter":
		return tea.KeyMsg{Type: tea.KeyEnter}
	case "q":
		return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("q")}
	default:
		return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(s)}
	}
}

func sampleModel() Model {
	items := worklist.Build([]discover.Credential{
		{Source: "git", Identity: "alice @ github.com", Kind: discover.KindToken},
		{Source: "ssh", Identity: "id_ed25519", Kind: discover.KindPrivateKey},
	})
	return New(items)
}

func TestNavigationAndDone(t *testing.T) {
	m := sampleModel()
	if m.cur != 0 {
		t.Fatalf("start cur=%d", m.cur)
	}

	// next
	nm, _ := m.Update(key("n"))
	m = nm.(Model)
	if m.cur != 1 {
		t.Errorf("after n, cur=%d want 1", m.cur)
	}
	// can't go past end
	nm, _ = m.Update(key("n"))
	m = nm.(Model)
	if m.cur != 1 {
		t.Errorf("n past end moved to %d", m.cur)
	}
	// prev
	nm, _ = m.Update(key("p"))
	m = nm.(Model)
	if m.cur != 0 {
		t.Errorf("after p, cur=%d want 0", m.cur)
	}
	// enter marks done and advances
	nm, _ = m.Update(key("enter"))
	m = nm.(Model)
	if !m.done[0] {
		t.Error("enter did not mark item 0 done")
	}
	if m.cur != 1 {
		t.Errorf("enter did not advance, cur=%d", m.cur)
	}
}

func TestQuit(t *testing.T) {
	m := sampleModel()
	nm, cmd := m.Update(key("q"))
	m = nm.(Model)
	if !m.quit {
		t.Error("q did not set quit")
	}
	if cmd == nil {
		t.Error("q should return a quit command")
	}
}

func TestViewContent(t *testing.T) {
	m := sampleModel()
	v := m.View()
	if !strings.Contains(v, "github.com") {
		t.Errorf("view missing identity/link:\n%s", v)
	}
	if !strings.Contains(v, "1 of 2") {
		t.Errorf("view missing progress:\n%s", v)
	}
	if !strings.Contains(v, "no secret") {
		t.Errorf("view missing read-only reassurance:\n%s", v)
	}
}

func TestEmptyModelView(t *testing.T) {
	if got := New(nil).View(); !strings.Contains(got, "No credentials") {
		t.Errorf("empty view = %q", got)
	}
}
