/// <reference lib="dom" />
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("Worktree checkout from a nested project protects the shared checkout", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Monorepo root");
  const git = (...args: string[]) => runPromise(run("git", args, { cwd: project }));
  await git("remote", "add", "origin", "https://gitlab.com/julius54/checkout-proof-47488-20261202.git");
  await git("fetch", "origin", "main", "review-source");
  await git("reset", "--hard", "origin/main");
  await git("checkout", "-b", "review-source", "02967424380540e6224b2e2bf316b56da405770c");
  const state = makeState(T3_HOME);
  await runPromise(state.cli(["project", "add", `${project}/package`, "--title", "Nested package"]));
  const thread = await t3.thread({ project: `${project}/package`, title: "Nested package work", messages: ["Start"] });
  await browser.setViewport({ width: 1280, height: 800 });
  await browser.addInitScript(() => {
    const ids = new Set<string>();
    const watched = new WeakSet<WebSocket>();
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      if (typeof data === "string") for (const request of [JSON.parse(data)].flat()) {
        if (request.tag === "git.preparePullRequestThread") ids.add(String(request.id));
      }
      if (!watched.has(this)) {
        watched.add(this);
        this.addEventListener("message", event => {
          if (typeof event.data !== "string") return;
          for (const reply of [JSON.parse(event.data)].flat()) {
            if (reply._tag === "Exit" && ids.has(String(reply.requestId))) document.documentElement.dataset.checkoutFinished = "true";
          }
        });
      }
      return send.call(this, data);
    };
  });
  await t3.open(thread);
  await screen.getByRole("button", "New thread", { exact: true }).tap();
  const projectPicker = browser.locator("[data-draft-project-trigger]");
  await projectPicker.waitFor();
  if ((await projectPicker.textContent())?.trim() !== "Nested package") {
    await projectPicker.tap();
    await screen.getByRole("option", "Nested package", { exact: true }).tap();
  }
  const picker = browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible').first();
  await picker.click();
  await screen.getByPlaceholder("Search refs...").fill("#1");
  await screen.getByRole("option", /Checkout merge request 1/).tap();
  await screen.getByRole("button", "Worktree", { exact: true }).tap();
  await browser.locator('html[data-checkout-finished="true"]').waitFor({ state: "attached" });
  await screen.getByRole("button", "Preparing worktree...", { exact: true }).waitFor({ state: "hidden" });
  await app.screenshot("nested-project-worktree-checkout");
  const head = (await git("rev-parse", "HEAD")).stdout.trim();
  expect(head).toBe("02967424380540e6224b2e2bf316b56da405770c");
  await expect(screen.getByText(/This PR branch is already checked out in the main repo/)).toBeVisible();
});
