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

const branch = "cursor/project-vite-migration-d966";
const mappings = [
  "+refs/heads/main:refs/remotes/origin/main",
  "+refs/heads/team/*:refs/remotes/origin/team/*",
  "+refs/heads/release/release-*:refs/remotes/origin/release/release-*",
];

test("Local PR checkout preserves restricted fetch mappings and sets upstream", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("t3-env");
  const git = (...args: string[]) => execFileSync("git", args, { cwd: project, encoding: "utf8" }).trim();
  git("remote", "add", "origin", "https://github.com/t3-oss/t3-env.git");
  git("fetch", "--depth=1", "origin", "main");
  git("reset", "--hard", "origin/main");
  git("config", "--unset-all", "remote.origin.fetch");
  for (const mapping of mappings) git("config", "--add", "remote.origin.fetch", mapping);
  const thread = await t3.thread({ project, title: "PR checkout reproduction", messages: ["Ready to check out the pull request."] });
  await t3.open(thread);
  await screen.getByRole("button", "New thread in t3-env", { exact: true }).tap();
  await screen.getByRole("region", "Thread details").getByRole("combobox", /^Branch:/).tap();
  await screen.getByPlaceholder("Search refs...").fill("https://github.com/t3-oss/t3-env/pull/406");
  await screen.getByText("Checkout pull request", { exact: true }).tap();
  await screen.getByRole("button", "Local", { exact: true }).tap();
  try {
    await expect(screen.getByRole("dialog")).toBeHidden({ timeout: 45_000 });
  } finally {
    await app.screenshot("local-checkout-result");
    const upstream = spawnSync("git", ["rev-parse", "--abbrev-ref", "@{upstream}"], { cwd: project, encoding: "utf8" });
    console.log(JSON.stringify({ currentBranch: git("branch", "--show-current"), upstream: upstream.stdout.trim(), upstreamError: upstream.stderr.trim(), fetchMappings: git("config", "--get-all", "remote.origin.fetch").split("\n") }));
  }
  expect(git("rev-parse", "--abbrev-ref", "@{upstream}")).toBe(`origin/${branch}`);
  expect(git("config", "--get-all", "remote.origin.fetch").split("\n")).toEqual([...mappings, `+refs/heads/${branch}*:refs/remotes/origin/${branch}*`]);
});
