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

test("Checkout refusal explains local changes and preserves the working copy", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("checkout-demo", { "notes.txt": "main committed content\n" });
  const git = (...args: string[]) => execFileSync("git", args, { cwd: project, encoding: "utf8" }).trim();
  git("checkout", "-b", "feature");
  writeFileSync(`${project}/notes.txt`, "feature committed content\n");
  git("add", "notes.txt");
  git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", "Feature content");
  git("checkout", "main");
  writeFileSync(`${project}/notes.txt`, "local uncommitted edit\n");
  await t3.open();
  await screen.getByRole("button", "New thread", { exact: true }).tap();
  await screen.getByRole("combobox", "Workspace", { exact: true }).tap();
  await screen.getByText("Current checkout", { exact: true }).last().tap();
  await screen.getByRole("region", "Message input").getByText("main", { exact: true }).tap();
  await screen.getByPlaceholder("Search refs...").fill("feature");
  await screen.getByText("feature", { exact: true }).tap();
  await screen.getByText("Failed to switch ref.", { exact: false }).waitFor({ state: "visible" });
  await browser.evaluate(async () => {
    await Promise.all(document.getAnimations().map((animation) => animation.finished.catch(() => {})));
  });
  await app.screenshot("checkout-refused");
  expect(git("branch", "--show-current")).toBe("main");
  expect(readFileSync(`${project}/notes.txt`, "utf8")).toBe("local uncommitted edit\n");
  await expect(screen.getByText("Your local changes would be overwritten by switching branches. Commit, stash, or discard them, then switch again.", { exact: false })).toBeVisible();
});
