import test from "node:test";
import assert from "node:assert/strict";
import { projectThreadGroups } from "./thread-groups.js";

test("linked account threads project as one latest chat row", () => {
  const threads = [
    { id: "thread-b", ownerId: "account-b", preview: "Injected handoff", updatedAt: "2026-07-01T01:00:00.000Z" },
    { id: "thread-a", ownerId: "account-a", preview: "Original request", updatedAt: "2026-07-01T00:00:00.000Z" },
    { id: "other", ownerId: "account-a", preview: "Other chat", updatedAt: "2026-06-30T23:00:00.000Z" }
  ];
  const sessions = [{
    id: "session-1",
    accountId: "account-b",
    codexThreadId: "thread-b",
    conversationTitle: "Original request",
    threadRefs: [
      { accountId: "account-a", threadId: "thread-a" },
      { accountId: "account-b", threadId: "thread-b" }
    ]
  }];

  assert.deepEqual(projectThreadGroups(threads, sessions), [
    {
      id: "thread-b",
      ownerId: "account-b",
      preview: "Original request",
      updatedAt: "2026-07-01T01:00:00.000Z",
      linkedSessionId: "session-1"
    },
    threads[2]
  ]);
});

test("a linked member on a later page uses stable current identity", () => {
  const sessions = [{
    id: "session-1", accountId: "account-b", codexThreadId: "thread-b",
    conversationTitle: "Original request",
    threadRefs: [{ accountId: "account-a", threadId: "thread-a" }, { accountId: "account-b", threadId: "thread-b" }]
  }];

  const [row] = projectThreadGroups([
    { id: "thread-a", ownerId: "account-a", preview: "Original request", updatedAt: "2026-07-01T00:00:00.000Z" }
  ], sessions);

  assert.equal(row.id, "thread-b");
  assert.equal(row.ownerId, "account-b");
  assert.equal(row.linkedSessionId, "session-1");
});

test("linked chat titles are sanitized before becoming public previews", () => {
  const [row] = projectThreadGroups([
    { id: "thread-b", ownerId: "account-b", preview: "Current", updatedAt: "2026-07-01T01:00:00.000Z" }
  ], [{
    id: "session-1",
    accountId: "account-b",
    codexThreadId: "thread-b",
    conversationTitle: "CODEX_HOME Bearer title-token C:\\Project\\Codex-remote\\auth.json",
    threadRefs: [{ accountId: "account-b", threadId: "thread-b" }]
  }], {
    workspaces: [{ path: "C:\\Project\\Codex-remote" }]
  });

  const serialized = JSON.stringify(row);
  assert.equal(serialized.includes("CODEX_HOME"), false);
  assert.equal(serialized.includes("auth.json"), false);
  assert.equal(serialized.includes("title-token"), false);
  assert.equal(serialized.includes("C:\\\\Project\\\\Codex-remote"), false);
  assert.equal(row.preview, "[redacted] Bearer [redacted] [private-path][redacted]");
});
