import { execFileSync } from "node:child_process";
import { symlinkSync } from "node:fs";
import { join } from "node:path";
import { T3_HOME } from "../e2e.config.ts";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Private Gitea pull request attachment renders", WEB, async ({ t3, app, screen, browser }) => {
  symlinkSync(process.env.GITEA_PROOF_FJ!, join(T3_HOME, "bin/fj"));
  const project = await t3.project("secret");
  const remote = process.env.GITEA_PROOF_REMOTE!;
  const token = process.env.GITEA_PROOF_TOKEN!;
  const git = (args: string[]) => execFileSync("git", args, { cwd: project, stdio: "pipe" });
  git(["remote", "add", "origin", remote]);
  git(["-c", `http.extraHeader=Authorization: Basic ${Buffer.from(`tester:${token}`).toString("base64")}`, "fetch", "origin", "main"]);
  git(["reset", "--hard", "FETCH_HEAD"]);
  await browser.emulateMedia({ colorScheme: "dark", reducedMotion: "reduce" });
  await t3.open();
  await screen.getByRole("button", "Pull requests", { exact: true }).tap();
  await screen.getByRole("searchbox", "Search pull requests").fill("secret");
  await browser.keyboard.press("Enter");
  await screen.getByText("Feature with screenshot", { exact: true }).tap();
  await screen.getByText("Screenshot below", { exact: true }).tap();
  try {
    await expect.poll(() => browser.evaluate(() => {
      const image = document.querySelector<HTMLImageElement>('img[alt="shot"]');
      return image?.complete ? image.naturalWidth : 0;
    }), { timeout: 15000 }).toBeGreaterThan(0);
  } finally {
    await app.screenshot("private-pr-attachment");
  }
});
