import { expect } from "e2e";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("MR checkout warns when another branch at the same commit takes over", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo", { "t3.json": JSON.stringify({ defaultThreadEnvMode: "local" }) });
  const git = (...args: string[]) => runPromise(run("git", args, { cwd: project }));
  const branch = "635002-send-tool-output";
  const head = "89391fea0f8749c251928308e69bb0b7f1bb5549";
  await git("remote", "add", "origin", "https://gitlab.com/gitlab-org/cli.git");
  await git("fetch", "--depth=2", "origin", "refs/merge-requests/4614/head");
  if ((await git("rev-parse", "FETCH_HEAD")).stdout.trim() !== head) throw new Error("Public MR head changed");
  await git("branch", branch, `${head}^`);
  await git("branch", "separate-work", head);
  const checkoutPath = `${project}-existing-worktree`;
  await git("worktree", "add", checkoutPath, branch);
  await t3.open("/");
  await browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible').first().click();
  await screen.getByPlaceholder("Search refs...").fill("#4614");
  const checkout = /Checkout (?:merge|pull|change) request/i;
  await screen.getByRole("option", checkout).tap();
  const dialog = screen.getByRole("dialog", checkout);
  await dialog.getByRole("button", "Worktree", { exact: true }).tap();
  await dialog.waitFor({ state: "hidden" });
  const actualBranch = (await git("-C", checkoutPath, "branch", "--show-current")).stdout.trim();
  if (actualBranch !== "separate-work") throw new Error(`Concurrent switch missed: ${actualBranch}`);
  await app.screenshot("checkout-result");
  expect(await screen.getByText("Checked out, but not confirmed on the latest commit", { exact: true }).isVisible()).toBe(true);
});
