/// <reference lib="dom" />
import { expect } from "e2e";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

const org = "t3code-factory-test";
const repo = "t3-factory-test";
const urls = [
  `https://dev.azure.com/${org}/${repo}/_git/${repo}/pullrequest/504`,
  `https://dev.azure.com/${org}/_git/${repo}/pullrequest/504`,
  `https://${org}.visualstudio.com/_git/${repo}/pullrequest/504`,
  `https://${org}.visualstudio.com/DefaultCollection/_git/${repo}/pullrequest/504`,
];

test("All Azure shorthand PR links open the SSH checkout's pull request panel", WEB, async ({ t3, app, browser, screen }) => {
  await browser.setViewport({ width: 1440, height: 1000 });
  const project = await t3.project(repo);
  await runPromise(run("git", ["remote", "add", "origin", `git@ssh.dev.azure.com:v3/${org}/${repo}/${repo}`], { cwd: project }));
  const thread = await t3.thread({ project, title: "Azure repository shorthand links", messages: [urls.map((url, i) => `${String.fromCharCode(65 + i)} ${url}`).join("\n\n")] });
  await t3.open(thread);
  await screen.getByRole("button", /^Agent A https:/).tap();
  await browser.locator(`a[href="${urls[0]}"]`).first().waitFor();
  const handled: boolean[] = [];
  for (let index = 0; index < urls.length; index++) {
    const url = urls[index]!;
    handled.push(await browser.evaluate((href) => {
      window.open = () => null;
      const link = [...document.querySelectorAll("a")].find(a => a.href === href)!;
      const event = new MouseEvent("click", { bubbles: true, cancelable: true, button: 0 });
      link.dispatchEvent(event);
      return event.defaultPrevented;
    }, url));
    if (handled[index]) {
      await screen.getByText("repro-44490 shorthand links", { exact: true }).first().waitFor({ timeout: 60000 });
    }
    await app.screenshot(`form-${String.fromCharCode(65 + index)}-after-click`);
    if (handled[index]) {
      await browser.evaluate(() => {
        const button = [...document.querySelectorAll<HTMLButtonElement>('button[aria-label^="Close "]')].find(b => b.getAttribute("aria-label")?.includes("504"));
        button?.click();
      });
    }
  }
  expect(handled, "Full URL and all three shorthand URLs must be handled inside the app").toEqual([true, true, true, true]);
});
