/// <reference lib="dom" />
import { copyFile, chmod, readFile } from "node:fs/promises";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("Load more retries a recovered Forgejo repository", WEB, async ({ t3, app, screen, browser }) => {
  // This is the official gt binary, talking to a real local Forgejo instance.
  const scratch = process.env.PROOF_SCRATCH!;
  await copyFile(`${scratch}/gt`, `${T3_HOME}/bin/gt`);
  await chmod(`${T3_HOME}/bin/gt`, 0o755);
  const token = (await readFile(`${scratch}/token`, "utf8")).trim();
  const setPulls = async (enabled: boolean) => {
    const response = await fetch("http://localhost:3947/api/v1/repos/demo/flaky", {
      method: "PATCH",
      headers: { Authorization: `token ${token}`, "Content-Type": "application/json" },
      body: JSON.stringify({ has_pull_requests: enabled }),
    });
    if (!response.ok) throw new Error(`Forgejo settings: ${response.status}`);
  };
  await setPulls(true);
  for (const name of ["steady", "flaky"]) {
    const project = await t3.project(name);
    await runPromise(run("git", ["remote", "add", "origin", `http://localhost:3947/demo/${name}.git`], { cwd: project }));
  }
  try {
    await t3.open("/pull-requests?host=localhost%3A3947&state=open&involvement=all");
    await screen.getByText("Flaky change 120", { exact: true }).waitFor();
    const more = screen.getByRole("button", "Load more pull requests", { exact: true });
    await more.waitFor();
    await setPulls(false);
    const failed = await fetch("http://localhost:3947/api/v1/repos/demo/flaky/pulls", { headers: { Authorization: `token ${token}` } });
    if (failed.status !== 404) throw new Error(`Expected Forgejo disabled pulls 404, got ${failed.status}`);
    await more.tap();
    await screen.getByText("Steady change 1", { exact: true }).waitFor();
    await setPulls(true);
    const recovered = await fetch("http://localhost:3947/api/v1/repos/demo/flaky/pulls?state=open&limit=50&page=3", { headers: { Authorization: `token ${token}` } });
    if (!recovered.ok || !(await recovered.json()).some((pr: { title: string }) => pr.title === "Flaky change 1")) throw new Error("Forgejo did not recover its oldest pull requests");
    await browser.evaluate(() => {
      for (const el of document.querySelectorAll<HTMLElement>("*")) {
        if (el.scrollHeight > el.clientHeight && ["auto", "scroll"].includes(getComputedStyle(el).overflowY)) el.scrollTop = el.scrollHeight;
      }
      return null;
    });
    await app.screenshot("load-more-after-temporary-failure");
    try {
      await expect(more).toBeVisible();
      await more.tap();
      await expect(screen.getByText("Flaky change 1", { exact: true })).toBeVisible();
    } finally {
      await browser.evaluate(() => {
        const titles = [...document.querySelectorAll<HTMLElement>("*")];
        const oldest = titles.find(el => el.textContent === "Flaky change 1")
          ?? titles.find(el => el.textContent === "Flaky change 22");
        oldest?.scrollIntoView({ block: "center" });
        return null;
      });
      await app.screenshot("forgejo-after-recovery");
    }
  } finally {
    await setPulls(true);
  }
});
