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

test("Confirmed main push refuses a checkout switched to feature", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("demo");
  const git = (...args: string[]) => execFileSync("git", args, { cwd: project, encoding: "utf8" }).trim();
  git("config", "user.name", "Scenario");
  git("config", "user.email", "scenario@example.invalid");
  const remote = `${project}/../remote.git`;
  git("init", "--bare", remote);
  git("remote", "add", "origin", remote);
  git("push", "-u", "origin", "main");
  git("switch", "-c", "feature");
  git("push", "-u", "origin", "feature");
  const initial = git("rev-parse", "HEAD");
  writeFileSync(`${project}/feature.txt`, "Feature work\n");
  git("add", "."); git("commit", "-m", "Feature work");
  git("switch", "main");
  writeFileSync(`${project}/main.txt`, "Main work\n");
  git("add", "."); git("commit", "-m", "Main work");
  const thread = await t3.thread({ project, title: "Confirmed push", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByRole("button", "Git action options").tap({ timeout: 120_000 });
  await screen.getByRole("menuitem", "Push", { exact: true }).tap();
  await screen.getByRole("button", "Push to main", { exact: true }).waitFor();
  await new Promise((resolve) => setTimeout(resolve, 1000));
  await app.screenshot("confirmation-main");
  git("switch", "feature");
  await screen.getByRole("button", "Push to main", { exact: true }).tap();
  await screen.getByText(/Pushed to origin\/feature|branch changed|Branch changed|expected.*main|Expected.*main|no longer.*main|changed from|no longer checked out/).first().waitFor({ timeout: 60_000 });
  await new Promise((resolve) => setTimeout(resolve, 1000));
  await app.screenshot("push-result");
  expect(git("--git-dir", remote, "rev-parse", "refs/heads/feature")).toBe(initial);
  expect(git("--git-dir", remote, "rev-parse", "refs/heads/main")).toBe(initial);
});
