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

test("Deleted Forgejo forks use a pull-request branch in a new worktree", WEB, async ({ t3, app, browser, screen }) => {
  copyFileSync(process.env.PROOF_FJ_BINARY!, `${T3_HOME}/bin/fj`);
  const project = await t3.project("project");
  const git = (...args: string[]) => runPromise(run("git", args, { cwd: project }));
  await git("remote", "add", "origin", "http://localhost:13300/maria/project.git");
  await git("fetch", "origin", "main");
  await git("reset", "--hard", "origin/main");
  await git("branch", "--set-upstream-to=origin/main", "main");
  await t3.open("/");
  await browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible').first().click();
  await screen.getByPlaceholder("Search refs...").fill("http://localhost:13300/maria/project/pulls/1");
  await screen.getByRole("option", /Checkout pull request/).tap();
  await screen.getByText("Add greeting from fork", { exact: true }).waitFor();
  await app.screenshot("deleted-fork-resolved");
  await screen.getByRole("button", "Worktree", { exact: true }).tap();
  await browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible').first().waitFor();
  // Wait for the dialog to finish preparing the checkout before inspecting its real Git refs.
  await screen.getByRole("dialog").waitFor({ state: "hidden" });
  await app.screenshot("deleted-fork-worktree");
  const refs = (await git("for-each-ref", "--format=%(refname)", "refs/heads")).stdout;
  expect(refs).not.toContain("refs/heads/refs/pull/1/head");
  expect(refs).toContain("refs/heads/t3code/pr-1/");
});
