import { expect } from "e2e";
import { execFileSync } from "node:child_process";
import { writeFileSync } from "node:fs";
import { test, WEB } from "./t3.ts";

const control = async (phase: string, fail = false) =>
  (await fetch(`http://127.0.0.1:19843/phase?name=${phase}&fail=${fail ? 1 : 0}`)).json();

test("All issues pages work when only the account lookup is unavailable", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Issues evidence");
  execFileSync("git", ["remote", "add", "origin", "https://github.com/pingdotgg/t3code.git"], { cwd: project });
  const thread = await t3.thread({ project, title: "Issue pagination evidence", messages: ["Ready"] });
  await t3.open(thread);
  await control("all-normal");
  const start = Date.now();
  await app.open("/issues?who=all&status=open");
  await screen.getByRole("button", "Load more").waitFor();
  const initialMs = Date.now() - start;
  await app.screenshot("initial-all-page");
  const continuationStart = Date.now();
  await screen.getByRole("button", "Load more").tap();
  await browser.locator('button:has-text("Evidence issue")').nth(99).waitFor({ state: "attached" });
  const continuationMs = Date.now() - continuationStart;
  await app.screenshot("two-all-pages");
  const normal = await control("assigned");
  for (const who of ["assigned", "authored", "mentioned"]) {
    await control(who);
    await app.open(`/issues?who=${who}&status=open`);
    await browser.locator('section').filter({ hasText: /Evidence issue|No issues under these filters/ }).first().waitFor();
    await app.screenshot(`${who}-account-filter`);
  }
  const filtered = await control("all-account-failure", true);
  await app.open("/issues?who=all&status=open");

  await browser.locator('button[aria-label="Refresh issues"]:not([disabled])').waitFor();
  // Wait for the response's UI state, which differs only in the broken behavior.
  await browser.locator('section').filter({ hasText: /Evidence issue|GitHub issue request failed|unreadable getViewer/ }).first().waitFor();
  await app.screenshot("account-lookup-unavailable");
  const failed = await control("finished");
  writeFileSync(`${process.env.EVIDENCE_OUTPUT_DIR}/observed-${Date.now()}.json`, JSON.stringify({ initialMs, continuationMs, normal, filtered, failed }, null, 2));
  await expect(browser.locator('button:has-text("Evidence issue")')).toHaveCount(50);
  expect(normal.requests.filter((r: { operation: string }) => /IssueViewer|IssueSearch/.test(r.operation)).map((r: { operation: string }) => r.operation)).toEqual(["IssueSearch", "IssueSearch"]);
});
