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

test("Checkout explains conflicting tracked edits", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("checkout-demo", { "notes.txt": "main content\n" });
  const git = (...args: string[]) => execFileSync("git", args, { cwd: project, encoding: "utf8" }).trim();
  git("checkout", "-b", "feature");
  writeFileSync(`${project}/notes.txt`, "feature 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`, "uncommitted local edits\n");
  await t3.open();
  await screen.getByRole("button", "New thread in checkout-demo", { exact: true }).tap();
  await screen.getByRole("combobox", "Workspace", { exact: true }).tap();
  await screen.getByRole("option", "Current checkout", { exact: true }).tap();
  await screen.getByRole("combobox", "Branch: main").first().tap();
  await screen.getByText("feature", { exact: true }).tap();
  await screen.getByText("Failed to switch ref.", { exact: true }).waitFor({ state: "visible" });
  if (git("branch", "--show-current") !== "main" || readFileSync(`${project}/notes.txt`, "utf8") !== "uncommitted local edits\n") throw new Error("Checkout changed branch or local edits");
  await new Promise((resolve) => setTimeout(resolve, 1200));
  await app.screenshot("checkout-conflict");
  await expect(screen.getByText("Your local changes would be overwritten by switching branches. Commit, stash, or discard them, then switch again.", { exact: false })).toBeVisible();
  if (git("branch", "--show-current") !== "main" || readFileSync(`${project}/notes.txt`, "utf8") !== "uncommitted local edits\n") throw new Error("Checkout changed branch or local edits");
});
