import { execFileSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

// Synthetic Azure repositories are prepared by the accompanying setup script.
test("Azure literal tool.git lists its own PR over HTTPS and SSH remotes", WEB, async ({ t3, app, screen }) => {
  const fixtures = JSON.parse(readFileSync(process.env.AZURE_PROOF_FIXTURES!, "utf8"));
  const literal = fixtures.find((repo: {name: string}) => repo.name === "tool.git");
  const projects = [];
  for (const transport of ["https", "ssh"]) {
    const project = await t3.project(`Azure tool.git ${transport.toUpperCase()}`);
    const git = (...args: string[]) => execFileSync("git", ["-C", project, ...args], { stdio: "pipe" });
    git("remote", "add", "origin", literal.https);
    git("-c", 'credential.helper=!f() { echo username=pat; echo "password=$AZURE_DEVOPS_EXT_PAT"; }; f', "fetch", "origin", "main");
    git("reset", "--hard", "FETCH_HEAD");
    git("remote", "set-url", "origin", literal[transport]);
    const thread = await t3.thread({project, title: `Inspect literal tool.git (${transport.toUpperCase()})`, messages: ["Ready to inspect repository pull requests."]});
    projects.push({thread, transport});
  }
  const listed = [];
  for (const {thread, transport} of projects) {
    await t3.open(thread);
    await screen.getByRole("textbox").fill("#");
    const options = screen.getByRole("option").filter({hasText: "repository PR"});
    await options.first().waitFor({timeout: 60_000});
    listed.push(await options.allTextContents());
    await app.screenshot(`azure-${transport}-pr-picker`);
  }
  await expect(listed, "Each literal tool.git remote must list its own PR").toEqual([
    [expect.stringContaining("Literal tool.git repository PR")],
    [expect.stringContaining("Literal tool.git repository PR")],
  ]);
});
