import { expect } from "e2e";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("Project-less Azure PR URLs offer checkout and resolve in the checkout dialog", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Azure checkout demo");
  const repo = "https://dev.azure.com/t3code-factory-test/t3-factory-test/_git/t3-factory-test";
  const git = (args: string[]) => runPromise(run("git", args, { cwd: project }));
  await git(["remote", "add", "origin", repo]);
  await git(["-c", 'credential.helper=!f() { echo username=pat; echo "password=$AZURE_DEVOPS_EXT_PAT"; }; f', "fetch", "origin", "main"]);
  await git(["reset", "--hard", "FETCH_HEAD"]);
  await browser.setViewport({ width: 1440, height: 1000 });
  await t3.open();
  const branch = browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible').first();
  const checkoutLabel = /Checkout (?:pull|change) request/i;
  const urls = [
    "https://dev.azure.com/t3code-factory-test/_git/t3-factory-test/pullrequest/433",
    "https://t3code-factory-test.visualstudio.com/_git/t3-factory-test/pullrequest/433",
  ];
  const accepted: boolean[] = [];
  for (const [index, url] of urls.entries()) {
    await branch.click();
    await screen.getByPlaceholder("Search refs...").fill(url);
    await screen.getByRole("option", /Create new ref/).waitFor();
    await app.screenshot(`branch-picker-${index === 0 ? "azure" : "legacy"}`);
    accepted.push(await screen.getByRole("option", checkoutLabel).isVisible());
    await browser.keyboard.press("Escape");
  }
  await branch.click();
  await screen.getByPlaceholder("Search refs...").fill(`${repo}/pullrequest/433`);
  await screen.getByRole("option", checkoutLabel).tap();
  const dialog = screen.getByRole("dialog", checkoutLabel);
  await dialog.getByText("Project-less URL checkout evidence", { exact: true }).waitFor({ timeout: 60000 });
  for (const [index, url] of urls.entries()) {
    await dialog.getByRole("textbox").fill(url);
    await dialog.getByText(/Project-less URL checkout evidence|Use a pull request URL/).waitFor({ timeout: 60000 });
    await app.screenshot(`checkout-dialog-${index === 0 ? "azure" : "legacy"}`);
    accepted.push(await dialog.getByRole("button", "Local", { exact: true }).isEnabled());
    accepted.push(await dialog.getByRole("button", "Worktree", { exact: true }).isEnabled());
  }
  expect(accepted, "Both project-less Azure URL formats offer checkout and resolve with Local and Worktree enabled").toEqual([true, true, true, true, true, true]);
});
