package workbenchruntime

import "strings"
import "testing"

func TestWorkbenchRuntimeReadIndexesCoverTraceFanout(t *testing.T) {
	want := []string{
		"idx_workbench_sessions_last_trace_updated",
		"idx_workbench_messages_trace_updated",
		"idx_workbench_parts_trace_updated",
		"idx_workbench_turns_trace_updated",
		"idx_workbench_projection_checkpoints_trace_updated",
	}
	joined := strings.Join(workbenchRuntimeReadIndexes, "\n")
	for _, name := range want {
		if !strings.Contains(joined, name) {
			t.Fatalf("workbench runtime trace fanout index %s is not ensured", name)
		}
	}
}

func TestSessionSummaryUsesNewestTurnFactsOverStaleSessionLastTrace(t *testing.T) {
	sessionID := "ses_triad_current_trace"
	oldTraceID := "trc_triad_completed"
	newTraceID := "trc_triad_running"
	facts := emptyFacts()
	facts["messages"] = []any{
		map[string]any{"messageId": "msg_old_user", "sessionId": sessionID, "traceId": oldTraceID, "role": "user", "status": "sent", "updatedAt": "2026-07-01T00:00:00Z", "projectedSeq": int64(10)},
		map[string]any{"messageId": "msg_old_agent", "sessionId": sessionID, "traceId": oldTraceID, "role": "agent", "status": "completed", "text": "first done", "updatedAt": "2026-07-01T00:00:02Z", "projectedSeq": int64(20)},
		map[string]any{"messageId": "msg_new_user", "sessionId": sessionID, "traceId": newTraceID, "role": "user", "status": "sent", "updatedAt": "2026-07-01T00:00:03Z", "projectedSeq": int64(30)},
		map[string]any{"messageId": "msg_new_agent", "sessionId": sessionID, "traceId": newTraceID, "role": "agent", "status": "running", "updatedAt": "2026-07-01T00:00:04Z", "projectedSeq": int64(40)},
	}
	facts["turns"] = []any{
		map[string]any{"turnId": oldTraceID, "sessionId": sessionID, "traceId": oldTraceID, "status": "completed", "terminal": true, "updatedAt": "2026-07-01T00:00:02Z", "projectedSeq": int64(20)},
		map[string]any{"turnId": newTraceID, "sessionId": sessionID, "traceId": newTraceID, "status": "running", "terminal": false, "updatedAt": "2026-07-01T00:00:04Z", "projectedSeq": int64(40)},
	}
	summary := sessionSummary(map[string]any{
		"sessionId":   sessionID,
		"ownerUserId": "usr_triad",
		"status":      "completed",
		"lastTraceId": oldTraceID,
		"updatedAt":   "2026-07-01T00:00:02Z",
	}, facts)

	if got := text(summary["lastTraceId"]); got != newTraceID {
		t.Fatalf("lastTraceId=%q, want %q; summary=%#v", got, newTraceID, summary)
	}
	if got := text(summary["status"]); got != "running" {
		t.Fatalf("status=%q, want running; summary=%#v", got, summary)
	}
	turnSummary := objectMap(summary["turnSummary"])
	if got := text(turnSummary["traceId"]); got != newTraceID {
		t.Fatalf("turnSummary.traceId=%q, want %q; turnSummary=%#v", got, newTraceID, turnSummary)
	}
	if got := text(turnSummary["status"]); got != "running" {
		t.Fatalf("turnSummary.status=%q, want running; turnSummary=%#v", got, turnSummary)
	}
}
