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

test("Git 2.24 commits only the selected files", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("selected-files", {
    "a.txt": "original a\n", "b.txt": "original b\n", "c.txt": "original c\n",
  });
  const git = (...args: string[]) => execFileSync(process.env.SCENARIO_OLD_GIT!, args, { cwd: project, encoding: "utf8" }).trim();
  console.log(git("--version"));
  git("init");
  git("config", "user.name", "Scenario");
  git("config", "user.email", "scenario@example.invalid");
  git("checkout", "-b", "selected-file-proof");
  for (const file of ["a.txt", "b.txt", "c.txt"]) await appendFile(`${project}/${file}`, "added line\n");
  const thread = await t3.thread({ project, title: "Git 2.24 selected-file commit", messages: ["first"] });
  await t3.open(thread);
  await screen.getByRole("button", "Git action options").tap();
  await screen.getByRole("menuitem", "Commit", { exact: true }).tap();
  await screen.getByRole("button", "Edit", { exact: true }).tap();
  await browser.locator('div:has(> button[aria-label="Open c.txt in editor"]) [role="checkbox"]').tap();
  await screen.getByPlaceholder("Leave empty to auto-generate").fill("Commit a and b only");
  await app.screenshot("selected-files-before-commit");
  await screen.getByRole("button", "Commit", { exact: true }).tap();
  await screen.getByText(/Action failed|Committed/).first().waitFor({ timeout: 60000 });
  await app.screenshot("selected-files-result");
  const result = {
    message: git("log", "-1", "--format=%s"),
    committedFiles: git("diff-tree", "--no-commit-id", "--name-only", "-r", "HEAD"),
    remaining: git("status", "--porcelain"),
    staged: git("diff", "--cached", "--name-only"),
  };
  console.log(JSON.stringify(result));
  expect(result).toEqual({ message: "Commit a and b only", committedFiles: "a.txt\nb.txt", remaining: "M c.txt", staged: "" });
});
