import test from "node:test";
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";

test("unified threads route projects linked account threads as logical chats", async () => {
  const source = await readFile(new URL("./index.js", import.meta.url), "utf8");
  assert.match(source, /import \{ projectThreadGroups \} from "\.\/thread-groups\.js"/);
  assert.match(source, /threads: projectThreadGroups\(result\.threads, listSessions\(\), config\)/);
});

test("unified threads route does not block the first page on full project history", async () => {
  const source = await readFile(new URL("./index.js", import.meta.url), "utf8");
  const routeStart = source.indexOf('if (req.method === "GET" && url.pathname === "/threads")');
  const routeEnd = source.indexOf('\n    if (req.method === "GET" && url.pathname === "/thread-projects")', routeStart);
  const routeBody = source.slice(routeStart, routeEnd);

  assert.ok(routeStart >= 0);
  assert.doesNotMatch(routeBody, /listAllUnifiedThreads/);
  assert.doesNotMatch(routeBody, /projectResult/);
});

test("project threads load incrementally from a separate paginated endpoint", async () => {
  const source = await readFile(new URL("./index.js", import.meta.url), "utf8");
  const routeStart = source.indexOf('url.pathname === "/thread-projects"');
  const routeBody = source.slice(routeStart, source.indexOf("const accountThreadsMatch", routeStart));

  assert.ok(routeStart >= 0);
  assert.match(routeBody, /listUnifiedThreads\(config, \{/);
  assert.match(routeBody, /cursor: url\.searchParams\.get\("cursor"\)/);
  assert.doesNotMatch(routeBody, /listAllUnifiedThreads/);
  assert.match(routeBody, /threads: projectThreadGroups\(result\.threads, listSessions\(\), config\)/);
  assert.match(routeBody, /hiddenProjects/);
});

test("project threads can be hidden without deleting history or workspaces", async () => {
  const source = await readFile(new URL("./index.js", import.meta.url), "utf8");
  const routeStart = source.indexOf('url.pathname === "/thread-projects/hide"');
  const routeBody = source.slice(routeStart, source.indexOf("const accountThreadsMatch", routeStart));

  assert.ok(routeStart >= 0);
  assert.match(routeBody, /projectPreferences\.hide/);
  assert.doesNotMatch(routeBody, /archive|rm|workspaces\s*=/);
});
