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

test("Encoded SSH .git suffix joins the literal suffix and no-suffix checkouts", WEB, async ({ t3, app, browser, screen }) => {
  const paths: string[] = [];
  for (const [title, remote] of [
    ["repo-literal", "ssh://git@gitlab.com/team/repo.git"],
    ["repo-encoded", "ssh://git@gitlab.com/team/repo%2Egit"],
    ["repo-nosuffix", "ssh://git@gitlab.com/team/repo"],
  ]) {
    const path = await t3.project(title!, { ".git/config": `[remote "origin"]\nurl = ${remote}\nfetch = +refs/heads/*:refs/remotes/origin/*\n` });
    paths.push(path);
  }

  // Redact only machine labels and generated absolute paths in rendered text; app state,
  // remote URLs, grouping, controls and their accessible names remain untouched.
  await browser.addInitScript(({ paths, machine }) => {
    const redact = () => {
      if (!document.body) return;
      const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
      while (walker.nextNode()) {
        const node = walker.currentNode;
        let text = node.nodeValue ?? "";
        for (const path of paths) text = text.replaceAll(path, `/demo/${path.split("/").at(-1)}`);
        text = text.replaceAll(machine, "Proof environment");
        if (node.nodeValue !== text) node.nodeValue = text;
      }
    };
    new MutationObserver(redact).observe(document, { childList: true, subtree: true, characterData: true });
  }, { paths, machine: hostname() });

  await t3.open("/settings/projects");
  await screen.getByRole("button", /^team\/repo/).waitFor();
  await app.screenshot("projects-list");
  await screen.getByRole("button", /^team\/repo/).tap();
  await screen.getByText("Checkouts", { exact: true }).waitFor();
  await screen.getByRole("combobox", /^Grouping rule for .*repo-nosuffix on/).waitFor();
  await browser.evaluate(() => {
    Array.from(document.querySelectorAll("h1,h2,h3,h4")).find((node) => node.textContent === "Checkouts")?.scrollIntoView({ block: "start" });
  });
  try {
    await expect(screen.getByRole("combobox", /^Grouping rule for .*repo-encoded on/)).toBeVisible();
  } finally {
    await app.screenshot("repository-checkout-grouping");
  }
});
