import test from "node:test";
import assert from "node:assert/strict";
import { activeSessionTitle, activeSessions, otherActiveSessions } from "./active-sessions.js";

test("activeSessions keeps only live sessions newest first", () => {
  const sessions = [
    { id: "completed", status: "completed", updatedAt: "2026-07-13T08:00:00.000Z" },
    { id: "running", status: "running", updatedAt: "2026-07-13T09:00:00.000Z" },
    { id: "approval", status: "waiting_approval", updatedAt: "2026-07-13T10:00:00.000Z" }
  ];

  assert.deepEqual(activeSessions(sessions).map((session) => session.id), ["approval", "running"]);
});

test("activeSessions prefers the current session over a stale polled copy", () => {
  const sessions = [
    { id: "same", status: "completed", updatedAt: "2026-07-13T09:00:00.000Z" },
    { id: "other", status: "waiting_response", updatedAt: "2026-07-13T10:00:00.000Z" }
  ];
  const currentSession = { id: "same", status: "running", updatedAt: "2026-07-13T11:00:00.000Z" };

  assert.deepEqual(activeSessions(sessions, currentSession).map((session) => session.id), ["same", "other"]);
});

test("activeSessions keeps the current chat visible during sending and thinking transitions", () => {
  assert.deepEqual(activeSessions([], { id: "sending", status: "sending" }).map((session) => session.id), ["sending"]);
  assert.deepEqual(activeSessions([], { id: "thinking", status: "thinking" }).map((session) => session.id), ["thinking"]);
});

test("otherActiveSessions excludes the currently open chat", () => {
  const sessions = [
    { id: "current", status: "running", updatedAt: "2026-07-13T11:00:00.000Z" },
    { id: "other", status: "waiting_approval", updatedAt: "2026-07-13T10:00:00.000Z" }
  ];

  assert.deepEqual(otherActiveSessions(sessions, sessions[0]).map((session) => session.id), ["other"]);
});

test("activeSessionTitle uses the matching safe chat title when the session title is missing", () => {
  const session = { accountId: "account-a", codexThreadId: "thread-a" };
  const threads = [
    { ownerId: "account-b", id: "thread-a", name: "Wrong account" },
    { ownerId: "account-a", id: "thread-a", name: "Current work" }
  ];

  assert.equal(activeSessionTitle(session, threads, "New chat"), "Current work");
  assert.equal(activeSessionTitle({ conversationTitle: "Session title" }, threads, "New chat"), "Session title");
});

test("activeSessionTitle uses a captured notification title before the slow chat list", () => {
  const session = { accountId: "account-a", codexThreadId: "thread-a" };
  const threads = [{ ownerId: "account-a", id: "thread-a", name: "Slow chat title" }];

  assert.equal(activeSessionTitle(session, threads, "New chat", "Captured chat title"), "Captured chat title");
});
