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

test("A sole github remote recognises trunk as its default branch", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("default-branch-demo", { "README.md": "Default branch demonstration\n" });
  const git = (...args: string[]) => execFileSync("git", args, { cwd: project, stdio: "pipe" });
  git("branch", "-m", "trunk");
  git("init", "--bare", "-b", "trunk", `${project}.git`);
  git("remote", "add", "github", `${project}.git`);
  git("push", "-u", "github", "trunk");
  git("remote", "set-head", "github", "trunk");
  await t3.thread({ project, title: "Default branch check", messages: ["Ready"] });
  appendFileSync(`${project}/README.md`, "A pending change on trunk.\n");
  await t3.open();
  await screen.getByRole("button", "Default branch check, Done, default-branch-demo").tap();
  const action = screen.getByRole("button", /^Commit.*push/).first();
  await app.screenshot("primary-git-action");
  await action.tap();
  await screen.getByText(/trunk is the base branch|Commit & push to default ref\?/).first().waitFor({ state: "visible" });
  await browser.evaluate(async () => {
    await Promise.all(document.getAnimations().filter((animation) => animation.effect?.getComputedTiming().iterations !== Infinity).map((animation) => animation.finished.catch(() => {})));
  });
  await app.screenshot("default-branch-action");
  await expect(screen.getByRole("heading", "Commit & push to default ref?")).toBeVisible();
  await app.screenshot("default-branch-confirmation");
});
