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

const ROOT = "https://gitlab.com/julius54/factory-pr-42605-proof/-/issues/";
test("GitLab incident and incident tab links open the same issue as the control", WEB, async ({t3, app, browser, screen}) => {
  await browser.emulateMedia({ colorScheme: "dark" });
  const project = await t3.project("Incident link proof");
  execFileSync("git", ["remote", "add", "origin", "https://gitlab.com/julius54/factory-pr-42605-proof.git"], {cwd:project});
  const thread = await t3.thread({project, title:"GitLab incident links", messages:[`Compare [Incident](${ROOT}incident/1), [Incident timeline](${ROOT}incident/1/timeline), and [Issue control](${ROOT}1).`]});
  await t3.open(thread);
  await screen.getByRole("button", /^Agent Compare/).tap();
  await screen.getByRole("link", "Issue control", {exact:true}).waitFor();
  await app.screenshot("incident-links-in-chat");
  const kinds = await browser.evaluate(() => ["Incident", "Incident timeline", "Issue control"].map(label => {
    const link = [...document.querySelectorAll("a")].find(a=>a.textContent === label);
    return {label, preview:link?.getAttribute("data-slot") === "preview-card-trigger", target:link?.getAttribute("target")};
  }));
  // Exercise all clicks before asserting so both recordings include the same interactions.
  await screen.getByRole("link", "Incident", {exact:true}).tap();
  if (kinds[0]?.preview) await screen.getByText("factory-pr-42605 checkout outage", {exact:true}).first().waitFor({timeout:60000});
  await app.screenshot("after-incident-click");
  await screen.getByRole("link", "Incident timeline", {exact:true}).tap();
  if (kinds[1]?.preview) await screen.getByText("factory-pr-42605 checkout outage", {exact:true}).first().waitFor({timeout:60000});
  await app.screenshot("after-incident-timeline-click");
  await screen.getByRole("link", "Issue control", {exact:true}).tap();
  await screen.getByText("factory-pr-42605 checkout outage", {exact:true}).first().waitFor({timeout:60000});
  await app.screenshot("control-issue-panel");
  expect(kinds.map(k=>k.preview), "Incident, timeline and control should all be issue preview triggers").toEqual([true,true,true]);
});
