/// <reference lib="dom" />
import { execFileSync } from "node:child_process";
import { writeFileSync } from "node:fs";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Repository aliases stay unique after loading the next page", WEB, async ({ t3, app, screen, browser }) => {
  await browser.addInitScript(`(() => {
    const tracked = new Set();
    window.__aliasEvidence = [];
    const Original = window.WebSocket;
    window.WebSocket = class extends Original {
      constructor(...args) {
        super(...args);
        let pending = "";
        this.addEventListener("message", event => {
          try {
            if (event.data.startsWith("\\u001e")) { pending += event.data.slice(1); return; }
            const frames = JSON.parse(pending + event.data);
            pending = "";
            for (const frame of (Array.isArray(frames) ? frames : [frames])) {
              if (tracked.has(String(frame.requestId))) window.__aliasEvidence.push({ direction: "answer", frame });
            }
          } catch {}
        });
      }
      send(data) {
        try {
          const frames = JSON.parse(data);
          for (const frame of (Array.isArray(frames) ? frames : [frames])) {
            if (frame.tag === "pullRequests.list") {
              tracked.add(String(frame.id));
              window.__aliasEvidence.push({ direction: "request", frame });
            }
          }
        } catch {}
        return super.send(data);
      }
    };
  })()`);
  let startingThread;
  for (const repository of ["zeit/swr", "vercel/swr"]) {
    const workspace = await t3.project(repository.replace("/", "-"), { ".git/config": `[remote "origin"]\nurl = https://github.com/${repository}.git\nfetch = +refs/heads/*:refs/remotes/origin/*\n` });
    execFileSync("git", ["fetch", "--depth=1", "origin", "main"], { cwd: workspace, stdio: "pipe" });
    startingThread = await t3.thread({ project: workspace, title: repository + " alias proof", messages: ["go"] });
  }
  await t3.open(startingThread);
  await screen.getByRole("button", "Pull requests").tap();
  await screen.getByRole("button", /^Sort pull requests/).tap();
  await screen.getByRole("menuitemradio", "Recently updated").tap();
  const more = screen.getByRole("button", "Load more pull requests");
  await more.waitFor({ state: "visible", timeout: 120_000 });
  const census = () => browser.evaluate(() => new Promise<Array<{key: string | null; text: string | null}>>(resolve => {
    const read = () => {
      const headings = [...document.querySelectorAll("h2")].filter(h => ["Others", "Authored", "Review requested"].includes(h.textContent ?? ""));
      const expected = headings.reduce((sum, h) => sum + Number(h.nextElementSibling?.textContent), 0);
      const rows = [...document.querySelectorAll("[data-pull-request-key]")];
      if (expected === 0 || rows.length !== expected) return false;
      resolve(rows.map(row => ({ key: row.getAttribute("data-pull-request-key"), text: row.textContent })));
      return true;
    };
    if (!read()) {
      const observer = new MutationObserver(() => { if (read()) observer.disconnect(); });
      observer.observe(document.body, { subtree: true, childList: true, characterData: true });
    }
  }));
  const first = await census();
  await app.screenshot("first-page");
  await more.tap();
  const continuation = screen.getByText("Loading more", { exact: true });
  await continuation.waitFor({ state: "visible", timeout: 20_000 });
  await app.screenshot("cursor-continuation");
  await continuation.waitFor({ state: "hidden", timeout: 120_000 });
  const final = await census();
  writeFileSync(`.e2e/alias-census-${Date.now()}.json`, JSON.stringify({ first, final, wire: await browser.evaluate("window.__aliasEvidence") }, null, 2));
  await app.screenshot("after-loading-more");
  await browser.evaluate(() => {
    const rows = [...document.querySelectorAll<HTMLElement>("[data-pull-request-key]")];
    const repeated = rows.find((row, i) => rows.some((other, j) => j < i && other.getAttribute("data-pull-request-key")?.split("#").pop() === row.getAttribute("data-pull-request-key")?.split("#").pop()));
    const target = repeated ?? rows.find(row => row.getAttribute("data-pull-request-key")?.endsWith("#2103")) ?? rows.at(-1);
    target?.scrollIntoView({ block: "center" });
  });
  await app.screenshot("alias-rows-detail");
  const numbers = final.map(row => row.key?.split("#").pop());
  expect(final.length).toBe(new Set(numbers).size);
});
