/// <reference lib="dom" />
import type { GitPreparePullRequestThreadResult } from "@t3tools/contracts";
import { expect } from "e2e";

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

declare global {
  interface Window {
    movedPrCheckout?: {
      readonly started: Promise<void>;
      readonly finish: () => void;
    };
  }
}

test(
  "Moving a draft cancels its waiting send and keeps the destination workspace",
  WEB,
  async ({ t3, app, browser, screen }) => {
    const project = await t3.project("demo", {
      "t3.json": JSON.stringify({ defaultThreadEnvMode: "local" }),
      ".git/config": '[remote "origin"]\n url = https://github.com/example/demo.git\n fetch = +refs/heads/*:refs/remotes/origin/*\n',
    });

    const other = await t3.project("other-project", {
      "t3.json": JSON.stringify({ defaultThreadEnvMode: "local" }),
    });
    await runPromise(run("git", ["branch", "-m", "develop"], { cwd: other }));
    const worktree = `${project}-review`;
    await runPromise(
      run("git", ["worktree", "add", "--quiet", "-b", "review-42", worktree], { cwd: project }),
    );

    const prepared: GitPreparePullRequestThreadResult = {
      branch: "review-42",
      worktreePath: worktree,
      isOnPullRequestHead: true,
      pullRequest: {
        number: 42,
        title: "Review branch",
        url: "https://github.com/example/demo/pull/42",
        headBranch: "review-42",
        baseBranch: "main",
        state: "open",
      },
    };
    await browser.addInitScript((value) => {
      const started = Promise.withResolvers<void>();
      const complete = Promise.withResolvers<void>();
      window.movedPrCheckout = { started: started.promise, finish: complete.resolve };

      const send = WebSocket.prototype.send;
      WebSocket.prototype.send = function (data) {
        const request: {
          _tag: string;
          tag: string;
          id: string;
        } | null = typeof data === "string" ? JSON.parse(data) : null;
        if (request?._tag !== "Request" || request.tag !== "git.preparePullRequestThread") {
          return send.call(this, data);
        }

        started.resolve();
        void complete.promise.then(() => {
          this.dispatchEvent(
            new MessageEvent("message", {
              data: JSON.stringify({
                _tag: "Exit",
                requestId: request.id,
                exit: { _tag: "Success", value },
              }),
            }),
          );
        });
      };
    }, prepared);

    // Two rounds run the workspace check before the waiting-send check, whose late
    // completion can navigate on base after its checkout is released.
    const results: Record<string, boolean> = {};
    for (const waitingSend of [false, true]) {
      await t3.open("/new?pr=example/demo/42");
      await screen.getByRole("button", "Check out", { exact: true }).tap();
      await browser.locator("[data-chat-provider-model-picker-label]").first().tap();
      await browser.keyboard.type("Multi turn");
      await browser.keyboard.press("Enter");
      await browser.keyboard.press("Escape");
      const composer = screen.getByRole("textbox");
      const prompt = "Explain the pull request changes";
      await composer.fill(prompt);
      await browser.evaluate(async () => {
        await window.movedPrCheckout?.started;
        return null;
      });
      if (waitingSend) {
        await composer.press("Enter");
        await app.screenshot("send-waiting-for-checkout");
      }
      const picker = browser.locator("[data-draft-project-trigger]");
      await picker.tap();
      await screen.getByRole("option", "other-project", { exact: true }).tap();
      await picker.filter({ hasText: "other-project" }).waitFor();
      const branch = browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible').first();
      await branch.filter({ hasText: "develop" }).waitFor();
      if (waitingSend) {
        // The checkout deliberately remains held throughout the cancellation and retry.
        await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 1500)));
        await app.screenshot("moved-draft-send-cancelled-before-checkout-finishes");
        results.cancelledImmediately = await browser.evaluate(() => document.body.innerText.includes("Draft changed while preparing this message. Review it and send again."));
        await composer.press("Enter");
        await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 8000)));
        await app.screenshot("retry-before-original-checkout-finishes");
        results.retryStarted = await browser.evaluate(() => !document.querySelector("[data-draft-project-trigger]"));
      }
      await browser.evaluate(() => {
        window.movedPrCheckout?.finish();
        return null;
      });
      await screen.getByText("Preparing the pull request checkout...", { exact: true }).waitFor({ state: "hidden" });
      if (!waitingSend) {
        await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 1000)));
        await app.screenshot("moved-draft-after-checkout");
        results.destinationBranchKept = await browser.evaluate(() => document.querySelector('[data-slot="combobox-trigger"][aria-label^="Branch:"]')?.textContent?.includes("develop") ?? false);
        results.promptKept = await browser.evaluate(() => document.querySelector('[role="textbox"]')?.textContent === "Explain the pull request changes");
        results.destinationWorkspaceKept = await browser.evaluate(() => document.body.innerText.includes("Current checkout") && !document.body.innerText.includes("Current worktree"));
      }
    }
    expect(results).toEqual({ cancelledImmediately: true, retryStarted: true, destinationBranchKept: true, promptKept: true, destinationWorkspaceKept: true });
  },
);
