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

test("Azure pull request checks out locally with its remote upstream", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("Azure checkout proof");
  const git = (...args: string[]) => execFileSync("git", args, { cwd: project, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
  git("remote", "add", "origin", process.env.PROOF_REMOTE!);
  git("config", "credential.helper", '!f() { echo username=pat; echo "password=$AZURE_DEVOPS_EXT_PAT"; }; f');
  git("fetch", "origin");
  git("reset", "--hard", "origin/main");
  git("branch", "--set-upstream-to=origin/main", "main");
  await t3.thread({ project, title: "Review checkout", messages: ["Prepare to review"] });
  await t3.open("/pull-requests?selectedUrl=" + encodeURIComponent(process.env.PROOF_PR_URL!));
  await screen.getByRole("button", /^Open #.*Local checkout proof/).tap();
  await screen.getByRole("button", "Check out", { exact: true }).tap();
  await screen.getByRole("menuitem", "In this repository", { exact: false }).tap();
  await screen.getByText(/Checked out here|Could not prepare the pull request checkout/, { exact: false }).first().waitFor({ state: "visible", timeout: 60000 });
  await app.screenshot("local-checkout-result");
  expect(git("branch", "--show-current")).toBe("proof-checkout");
  expect(git("rev-parse", "--abbrev-ref", "@{upstream}")).toBe("origin/proof-checkout");
});
