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

test("A closed fork pull request worktree starts at its recorded head", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("closed-pr-proof");
  const git = (...args: string[]) => execFileSync("git", args, { cwd: project, encoding: "utf8" }).trim();
  git("remote", "add", "origin", "https://github.com/pingdotgg/t3code.git");
  git("fetch", "--no-tags", fileURLToPath(new URL("../..", import.meta.url)), "refs/remotes/origin/main:refs/remotes/origin/main");
  git("reset", "--hard", "refs/remotes/origin/main");
  const recorded = git("ls-remote", "origin", "refs/pull/47231/head").split(/\s+/)[0];
  await t3.open("/");
  await browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible').first().click();
  await screen.getByPlaceholder("Search refs...").fill("47231");
  await screen.getByRole("option", /Checkout pull request/).click();
  await screen.getByText("#47231 · feat/boring-sidebar-folder-drag to main", { exact: true }).waitFor({ timeout: 60000 });
  await app.screenshot("closed-pr-resolved");
  await screen.getByRole("button", "Worktree", { exact: true }).click();
  await screen.getByRole("dialog", "Checkout pull request", { exact: true }).waitFor({ state: "hidden", timeout: 120000 });
  const entries = git("worktree", "list", "--porcelain").split("\n\n");
  const entry = entries.find(e => e.includes("branch refs/heads/t3code/pr-47231/"));
  const actual = entry?.match(/^HEAD (.+)$/m)?.[1] ?? "missing worktree";
  await app.screenshot("closed-pr-worktree-created");
  expect(actual).toBe(recorded);
});
