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

test("Commit completes a merge resolved to the current branch contents", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("Merge resolution", { "note.txt": "base\n" });
  const git = (...args: string[]) => execFileSync("git", args, { cwd: project, encoding: "utf8" }).trim();
  git("config", "user.name", "Scenario");
  git("config", "user.email", "scenario@example.invalid");
  git("checkout", "-b", "topic");
  writeFileSync(join(project, "note.txt"), "topic\n");
  git("commit", "-am", "Topic change");
  git("checkout", "main");
  writeFileSync(join(project, "note.txt"), "main\n");
  git("commit", "-am", "Main change");
  try { git("merge", "topic"); } catch { /* The expected conflict leaves MERGE_HEAD and an unmerged index. */ }
  writeFileSync(join(project, "note.txt"), "main\n");
  await t3.thread({ project, title: "Complete the resolved merge", messages: ["The conflict in note.txt is resolved by keeping main. Complete the merge with Commit."] });
  await t3.open();
  await screen.getByRole("button", { name: /^Complete the resolved merge,/ }).tap();
  await screen.getByRole("button", "Git action options").tap();
  await screen.getByRole("menuitem", "Commit").tap();
  await screen.getByPlaceholder("Leave empty to auto-generate").fill("Complete merge");
  await app.screenshot("resolved-merge-ready");
  await screen.getByRole("button", "Commit", { exact: true }).tap();
  // Wait for the real action's completion, including the erroneous no-op result.
  await screen.getByRole("dialog").waitFor({ state: "hidden" });
  await screen.getByRole("group", "Git actions").getByText(/^(Done|Committed [0-9a-f]+)$/).waitFor({ state: "visible" });
  await app.screenshot("commit-result");
  await expect.poll(() => ({ parents: git("rev-list", "--parents", "-n", "1", "HEAD").split(" ").length - 1, merging: existsSync(join(project, ".git", "MERGE_HEAD")) })).toEqual({ parents: 2, merging: false });
});
