import test from "node:test";
import assert from "node:assert/strict";
import { collectProjectHistory } from "./project-history.js";

test("project history is collected completely before it is returned to the UI", async () => {
  const requestedCursors = [];
  const firstPage = {
    threads: [{ id: "recent", ownerId: "a", updatedAt: "2026-07-18T02:00:00.000Z" }],
    hiddenProjects: [{ projectKey: "hidden", hiddenAt: "2026-07-18T01:00:00.000Z" }],
    errors: [],
    nextCursor: "page-2"
  };

  const result = await collectProjectHistory(firstPage, async (cursor) => {
    requestedCursors.push(cursor);
    return {
      threads: [{ id: "older", ownerId: "a", updatedAt: "2026-07-17T02:00:00.000Z" }],
      hiddenProjects: firstPage.hiddenProjects,
      errors: [],
      nextCursor: null
    };
  }, { yieldToMain: async () => {} });

  assert.deepEqual(requestedCursors, ["page-2"]);
  assert.deepEqual(result.threads.map((thread) => thread.id), ["recent", "older"]);
  assert.deepEqual(result.hiddenProjects, firstPage.hiddenProjects);
  assert.deepEqual(result.errors, []);
});

test("a superseded project history refresh stops without publishing partial data", async () => {
  let current = true;
  const firstPage = {
    threads: [{ id: "recent", ownerId: "a", updatedAt: "2026-07-18T02:00:00.000Z" }],
    errors: [],
    nextCursor: "page-2"
  };

  const result = await collectProjectHistory(firstPage, async () => {
    current = false;
    return {
      threads: [{ id: "older", ownerId: "a", updatedAt: "2026-07-17T02:00:00.000Z" }],
      errors: [],
      nextCursor: null
    };
  }, {
    isCurrent: () => current,
    yieldToMain: async () => {}
  });

  assert.equal(result, null);
});
