import { mergeThreadPage } from "../../thread-library.js";

export async function collectProjectHistory(seed, loadPage, options = {}) {
  const isCurrent = options.isCurrent ?? (() => true);
  const yieldToMain = options.yieldToMain ?? (() => new Promise((resolve) => setTimeout(resolve, 0)));
  const seenCursors = new Set();
  let page = seed;
  let cursor;
  let threads = [];
  let hiddenProjects = [];

  while (true) {
    if (!page) page = await loadPage(cursor);
    if (!isCurrent()) return null;

    threads = mergeThreadPage(threads, page.threads ?? []);
    if (Array.isArray(page.hiddenProjects)) hiddenProjects = page.hiddenProjects;
    const errors = page.errors ?? [];
    const nextCursor = page.nextCursor;
    if (errors.length > 0 || !nextCursor || seenCursors.has(nextCursor)) {
      return { threads, hiddenProjects, errors };
    }

    seenCursors.add(nextCursor);
    cursor = nextCursor;
    page = undefined;
    await yieldToMain();
    if (!isCurrent()) return null;
  }
}
