/// <reference lib="dom" />
import { execFileSync } from "node:child_process";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Azure DevOps checks out the exact source branch with trailing NBSP", WEB, async ({ t3, app, browser, screen }) => {
  const cwd = await t3.project("NBSP checkout proof");
  const git = (...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8", env: process.env });
  git("remote", "add", "origin", process.env.PROOF_REPO_URL!);
  git("config", "credential.helper", '!f() { echo username=pat; echo "password=$AZURE_DEVOPS_EXT_PAT"; }; f');
  git("fetch", "origin", "main");
  git("reset", "--hard", "origin/main");
  const thread = await t3.thread({ project: cwd, title: "Exact Azure branch checkout", model: "default", messages: [] });
  await browser.setViewport({ width: 1440, height: 1000 });
  await t3.open(thread);
  await t3.open("/pull-requests");
  await screen.getByText("NBSP checkout proof 45722", { exact: true }).tap();
  await screen.getByRole("button", "Check out", { exact: true }).waitFor();
  await screen.getByText("Temporary exact branch name checkout verification.", { exact: true }).waitFor();
  const branchText = await browser.evaluate(() => document.querySelector('[aria-label="Copy pull request branch"] code')?.textContent);
  await app.screenshot("source-branch-details");
  await screen.getByRole("button", "Check out", { exact: true }).tap();
  await screen.getByText("In this repository", { exact: true }).tap();
  await screen.getByText("Preparing the pull request checkout...", { exact: true }).waitFor();
  await screen.getByText("Preparing the pull request checkout...", { exact: true }).waitFor({ state: "hidden", timeout: 60000 });
  await app.screenshot("checkout-result");
  const branch = git("symbolic-ref", "--short", "HEAD").replace(/\n$/, "");
  expect(branch, "Checkout preserves trailing U+00A0").toBe(process.env.PROOF_BRANCH);
  expect(branchText, "Details preserve trailing U+00A0").toContain(process.env.PROOF_BRANCH!);
});
