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

const scratch = process.env.AZURE_PROOF_FIXTURE_DIR!;
test("Azure pull request local checkout switches branch and 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" }).trim();
  git("remote", "add", "origin", readFileSync(`${scratch}/remote-url`, "utf8").trim());
  git("config", "credential.helper", '!f() { echo username=pat; echo "password=$AZURE_DEVOPS_EXT_PAT"; }; f');
  git("fetch", "origin");
  git("switch", "--force-create", "proof-31170-base", "origin/proof-31170-base");
  const thread = await t3.thread({ project, title: "Azure checkout proof", messages: ["Ready for checkout"] });
  await t3.open(thread);
  await screen.getByRole("button", "New thread in azure-checkout-proof", { exact: true }).tap();
  await screen.getByRole("region", "Version Control").getByRole("combobox", "Branch: proof-31170-base").tap();
  await screen.getByRole("combobox", "Search refs...").fill(`#${readFileSync(`${scratch}/pr-id`, "utf8").trim()}`);
  await screen.getByText("Checkout pull request", { exact: true }).tap();
  await screen.getByRole("button", "Local", { exact: true }).tap();
  try {
    await expect.poll(() => ({ branch: git("branch", "--show-current"), upstream: git("rev-parse", "--abbrev-ref", "@{upstream}") }), { timeout: 15_000 }).toEqual({ branch: "proof-31170-change", upstream: "origin/proof-31170-change" });
    await expect(screen.getByRole("dialog", "Checkout pull request")).not.toBeVisible();
  } finally {
    console.log(JSON.stringify({ branch: git("branch", "--show-current"), upstream: git("rev-parse", "--abbrev-ref", "@{upstream}") }));
    await app.screenshot("local-checkout-result");
  }
});
