import * as fs from "node:fs/promises";
import { execFileSync } from "node:child_process";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Publishing under your own Forgejo name accepts every letter case", WEB, async ({t3, app, browser, screen}) => {
  await fs.symlink(process.env.PROOF_FJ!, `${T3_HOME}/bin/fj`);
  const host = "https://127.0.0.1:33248";
  const headers = {Authorization: `token ${process.env.PROOF_TOKEN}`, "Content-Type":"application/json"};
  const cases = [["alice", "lowercase"], ["ALICE", "uppercase"], ["Alice", "exact-case"], ["acme-org", "organization"]];
  const runs = [];
  for (const [owner, label] of cases) {
    await fetch(`${host}/api/v1/repos/${owner}/proof-${label}`, {method:"DELETE", headers});
    const project = await t3.project(`project-${label}`);
    execFileSync("git", ["config", "http.sslCAInfo", process.env.SSL_CERT_FILE!], {cwd:project});
    execFileSync("git", ["config", "credential.helper", '!f() { echo username=Alice; echo "password=$PROOF_TOKEN"; }; f'], {cwd:project});
    const thread = await t3.thread({project, title:`Publish ${label}`, messages:["Start"]});
    runs.push({owner, label, thread});
  }
  await t3.open("/settings/source-control");
  const offer = screen.getByRole("switch", "Offer Forgejo / Gitea when adding or publishing a project");
  await offer.tap();
  await app.screenshot("forgejo-authenticated");
  const published: boolean[] = [];
  for (const {owner, label, thread} of runs) {
    await t3.open(thread);
    await screen.getByRole("button", "Publish repository", {exact:true}).tap();
    await screen.getByRole("radio", "Forgejo / Gitea").tap();
    await screen.getByRole("button", "Next", {exact:true}).tap();
    await browser.locator("#publish-repository-path").fill(`${owner}/proof-${label}`);
    await screen.getByRole("button", "Advanced", {exact:true}).tap();
    await screen.getByRole("button", "HTTPS", {exact:true}).tap();
    await screen.getByRole("button", "Publish", {exact:true}).tap();
    await screen.getByText(/^(Publish failed|Repository published|Repository created)$/, {exact:true}).waitFor({timeout:60000});
    await browser.evaluate(async () => {
      await Promise.all(document.getAnimations().filter((animation) => animation.effect?.getTiming().iterations !== Infinity).map((animation) => animation.finished.catch(() => {})));
      await new Promise<void>((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
      return null;
    });
    await app.screenshot(`publish-${label}`);
    published.push(await browser.evaluate(() => Array.from(document.querySelectorAll("h3")).some((heading) => heading.textContent === "Repository published")));
    await browser.keyboard.press("Escape");
  }
  await expect(published).toEqual([true, true, true, true]);
});
