import { readFile } from "node:fs/promises";
import { expect } from "e2e";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("A completed request reuses its recorded head after the source branch advances", WEB, async ({ t3, app, browser, screen }) => {
  const fixture = JSON.parse(await readFile(process.env.PROOF_FIXTURE!, "utf8"));
  const project = await t3.project("review-demo", { "t3.json": JSON.stringify({ defaultThreadEnvMode: "local" }) });
  const git = (...args: string[]) => runPromise(run("git", args, { cwd: project }));
  await git("remote", "add", "origin", fixture.url);
  await git("config", "credential.helper", '!f() { echo username=pat; echo "password=$AZURE_DEVOPS_EXT_PAT"; }; f');
  await git("fetch", "origin", "main", "review-source");
  const checkout = `${project}-review`;
  await git("branch", "review-source", fixture.recorded);
  await git("branch", "--set-upstream-to=origin/review-source", "review-source");
  await git("worktree", "add", checkout, "review-source");
  await t3.open("/");
  await browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible').first().click();
  await screen.getByPlaceholder("Search refs...").fill(`#${fixture.pr}`);
  const action = /Checkout (?:merge|pull|change) request/i;
  await screen.getByRole("option", action).tap();
  const dialog = screen.getByRole("dialog", action);
  await dialog.getByText("Changes for review", { exact: true }).waitFor();
  await app.screenshot("completed-request-dialog");
  await dialog.getByRole("button", "Worktree", { exact: true }).tap();
  await dialog.waitFor({ state: "hidden" });
  const actual = (await runPromise(run("git", ["rev-parse", "HEAD"], { cwd: checkout }))).stdout.trim();
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("review.txt");
  await screen.getByRole("option", "review.txt", { exact: false }).tap();
  const editorText = () => browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const content = host.shadowRoot?.querySelector("[data-content]");
      if (content) return content.textContent ?? "";
    }
    return null;
  });
  try {
    await expect.poll(editorText, { timeout: 30000 }).toContain("Head at merge");
    expect(actual).toBe(fixture.recorded);
  } finally {
    await app.screenshot("completed-request-reused-worktree");
  }
});
