import { writeFile } from "node:fs/promises";
import { expect } from "e2e";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("Push republishes a deleted remote branch at local HEAD", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("Republish demo", { "a.txt": "initial\n", "b.txt": "initial\n" });
  const git = (...args: string[]) => runPromise(run("git", args, { cwd: project })).then(r => r.stdout.trim());
  await git("config", "user.name", "Scenario");
  await git("config", "user.email", "scenario@example.invalid");
  await git("init", "--bare", `${project}/../remote.git`);
  await git("remote", "add", "origin", "../remote.git");
  await git("push", "-u", "origin", "main");
  await git("checkout", "-b", "feature/republish");
  await writeFile(`${project}/a.txt`, "feature\n");
  await git("commit", "-am", "Feature change");
  await git("push", "-u", "origin", "feature/republish");
  await git("push", "origin", "--delete", "feature/republish");
  await git("fetch", "--prune");
  await writeFile(`${project}/b.txt`, "new change\n");
  const thread = await t3.thread({ project, title: "Republish deleted branch", messages: ["Ready to publish"] });
  await t3.open(thread);
  await screen.getByRole("button", "Git action options").tap();
  await screen.getByRole("menuitem", "Commit", { exact: true }).tap();
  await screen.getByPlaceholder("Leave empty to auto-generate").fill("add b");
  await screen.getByRole("button", "Commit", { exact: true }).tap();
  await screen.getByText("Committed", { exact: false }).waitFor({ state: "visible" });
  await screen.getByRole("button", "Git action options").tap();
  await screen.getByRole("menuitem", "Push", { exact: true }).tap();
  await screen.getByText(/^(Done|Pushed\b)/).waitFor({ state: "visible" });
  await app.screenshot("push-result");
  const head = await git("rev-parse", "HEAD");
  const remote = await git("ls-remote", "origin", "refs/heads/feature/republish");
  await expect(remote.split(/\s/)[0]).toBe(head);
});
