package app

import (
	"testing"

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

func TestAgoLabel(t *testing.T) {
	cases := []struct {
		ms   int64
		want string
	}{
		{-100, "0s ago"},
		{0, "0s ago"},
		{3_000, "3s ago"},
		{59_000, "59s ago"},
		{90_000, "1m ago"},
		{3_600_000, "1h ago"},
		{90_000_000, "1d ago"},
	}
	for _, c := range cases {
		if got := agoLabel(c.ms); got != c.want {
			t.Errorf("agoLabel(%d) = %q, want %q", c.ms, got, c.want)
		}
	}
}

// An event type this client doesn't recognize must still surface as a raw row in the
// session's event stream — never silently dropped (TUI-requirements §2).
func TestUnknownEventSurfacesAsRawRow(t *testing.T) {
	m := NewModel(nil)
	m.applyServer(protocol.ServerMessage{
		Type:       "some.future.event",
		SessionID:  "s1",
		OccurredAt: 1_700_000_000_000,
	})

	s := m.session("s1")
	if s == nil {
		t.Fatalf("unknown event did not vivify its session")
	}
	if len(s.Events) != 1 {
		t.Fatalf("expected 1 raw event row, got %d", len(s.Events))
	}
	if s.Events[0].Type != "some.future.event" {
		t.Errorf("raw row type = %q, want the unknown type verbatim", s.Events[0].Type)
	}
}

// router.response is recognized-but-intentionally-not-rendered on the global stream;
// it must NOT be misclassified as an unknown event and spawn a spurious row.
func TestKnownIgnoredEventDoesNotSpawnRow(t *testing.T) {
	m := NewModel(nil)
	m.applyServer(protocol.ServerMessage{
		Type:      protocol.TypeRouterResponse,
		SessionID: "s1",
		Content:   "superseded by chat.turn",
	})

	if len(m.sessions) != 0 {
		t.Fatalf("router.response should not vivify a session, got %d", len(m.sessions))
	}
}
