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

test("Selecting a stale worktree branch checks out the selected branch", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("branch-switch-demo");
  const git = (cwd: string, ...args: string[]) => execFileSync("git", ["-C", cwd, ...args], { encoding: "utf8" }).trim();
  const worktree = `${project}-wt-a`;
  git(project, "branch", "feature/a");
  git(project, "branch", "feature/b");
  git(project, "worktree", "add", worktree, "feature/a");
  const thread = await t3.thread({ project, title: "Select the previous branch", messages: ["Show the fixture"] });
  await t3.open(thread);
  await screen.getByRole("combobox", "Branch: main").tap();
  // Keep the mounted listing while another checkout changes under it.
  await app.screenshot("picker-before-external-checkout");
  git(worktree, "switch", "feature/b");
  await new Promise(resolve => setTimeout(resolve, 50_000));
  await app.screenshot("stale-worktree-claim");
  await screen.getByRole("option", "feature/ a worktree").tap();
  await new Promise(resolve => setTimeout(resolve, 5_000));
  await app.screenshot("selected-branch-result");
  await expect(screen.getByRole("combobox", "Branch: feature/a")).toBeVisible();
  // The UI must describe a checkout actually on the selected branch.
  const checkedOut = [git(project, "branch", "--show-current"), git(worktree, "branch", "--show-current")];
  expect(checkedOut.includes("feature/a")).toBe(true);
});
