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

test("Publish keeps a local branch's other-remote prefix", WEB, async ({ t3, app, screen }) => {
  const repo = await t3.project("publish-demo");
  const git = (...args: string[]) => execFileSync("git", args, { cwd: repo, encoding: "utf8" }).trim();
  const origin = `${repo}-origin.git`;
  const alice = `${repo}-alice.git`;
  git("init", "--bare", origin);
  git("init", "--bare", alice);
  git("remote", "add", "origin", origin);
  git("remote", "add", "alice", alice);
  git("push", "origin", "main");
  git("symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main");
  git("checkout", "--no-track", "-b", "alice/fix");
  writeFileSync(`${repo}/fix.txt`, "Add fix\n");
  git("add", "fix.txt");
  git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", "Add fix");
  const thread = await t3.thread({ project: repo, title: "Publish alice/fix", messages: ["hello"], model: "command-output" });
  await t3.open(thread);
  await screen.getByRole("button", "Git action options").tap();
  await screen.getByRole("menuitem", "Push", { exact: true }).tap();
  await screen.getByText("Pushed to", { exact: false }).waitFor({ state: "visible" });
  await app.screenshot("published-branch");
  const refs = git("ls-remote", "--heads", "origin");
  const upstream = git("rev-parse", "--abbrev-ref", "@{upstream}");
  await expect(refs).toContain("refs/heads/alice/fix");
  await expect(upstream).toBe("origin/alice/fix");
});
