/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

declare global { interface Window { linkHold: { requested: Promise<void>; release: () => Promise<string> } } }

test("Link dialog belongs to one opening on one thread", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo");
  const a = await t3.thread({ project, title: "Thread A Hello", model: "default", messages: ["Thread A prompt"] });
  const b = await t3.thread({ project, title: "Thread B Hello", model: "default", messages: ["Thread B prompt"] });
  await browser.addInitScript(() => {
    let forward = () => {};
    let requested = Promise.withResolvers<void>();
    let replied = Promise.withResolvers<string>();
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      if (typeof data !== "string" || !data.includes('"thread.pull-request.link"')) return send.call(this, data);
      const request = JSON.parse(data);
      this.addEventListener("message", event => {
        const exit = [JSON.parse(String(event.data))].flat().find(frame => frame._tag === "Exit" && String(frame.requestId) === String(request.id));
        if (exit) replied.resolve(String(exit.exit?._tag));
      });
      forward = () => send.call(this, data);
      requested.resolve();
    };
    window.linkHold = { get requested() { return requested.promise; }, release: async () => {
      forward();
      const result = await replied.promise;
      requested = Promise.withResolvers<void>(); replied = Promise.withResolvers<string>();
      await new Promise(resolve => setTimeout(resolve, 700));
      return result;
    } };
  });
  await t3.open(b);
  await screen.getByText("Thread B prompt", { exact: true }).waitFor();
  const palette = screen.getByRole("dialog", "Command palette");
  const dialog = screen.getByRole("dialog", "Link pull request", { exact: true });
  const input = screen.getByPlaceholder("Pull request URL or #42");
  const command = async (text: string) => {
    await browser.keyboard.press("Control+k");
    await palette.getByRole("combobox").fill(text);
    await palette.getByRole("option", new RegExp(text.replace(/^> /, ""))).tap();
    await palette.waitFor({ state: "hidden" });
    await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 700)));
  };
  const open = () => command("> Link pull request to thread");
  const go = (title: string) => command(title);
  const results: Record<string, boolean> = {};
  await open();
  await input.fill("https://github.com/pingdotgg/t3code/pull/12345");
  await app.screenshot("01-dialog-on-thread-b");
  await go("Thread A Hello");
  await app.screenshot("02-after-leaving-for-thread-a");
  results.closesOnLeave = !(await dialog.isVisible());
  await go("Thread B Hello");
  await app.screenshot("03-return-to-thread-b");
  results.returnDoesNotReopen = !(await dialog.isVisible());
  if (await dialog.isVisible()) await screen.getByRole("button", "Cancel", { exact: true }).tap();
  await open();
  results.reopensEmpty = await input.getAttribute("value") === "";
  await app.screenshot("04-explicit-reopen-empty");
  await input.fill("https://github.com/pingdotgg/t3code/pull/12345");
  await open();
  results.secondOpenKeepsInput = await input.getAttribute("value") === "https://github.com/pingdotgg/t3code/pull/12345";
  await app.screenshot("05-second-open-same-thread");
  await screen.getByRole("button", "Link", { exact: true }).tap();
  await browser.evaluate(() => window.linkHold.requested.then(() => null));
  await app.screenshot("06-old-submission-pending");
  await go("Thread A Hello");
  await command("> Open pull requests");
  await app.screenshot("06a-pull-requests-page-during-old-submission");
  await go("Thread A Hello");
  await app.screenshot("06b-return-from-pull-requests");
  results.pullRequestsReturnDoesNotReopen = !(await dialog.isVisible());
  if (await dialog.isVisible()) await screen.getByRole("button", "Cancel", { exact: true }).tap();
  await go("Thread B Hello");
  await open();
  await input.fill("https://github.com/pingdotgg/t3code/pull/999");
  await app.screenshot("07-new-opening-before-old-reply");
  const oldReply = await browser.evaluate(() => window.linkHold.release());
  await app.screenshot("08-new-opening-after-old-reply");
  results.oldReplyKeepsNewOpening = oldReply === "Success" && await dialog.isVisible();
  if (await dialog.isVisible()) await screen.getByRole("button", "Cancel", { exact: true }).tap();
  await open();
  await input.fill("https://github.com/pingdotgg/t3code/pull/12346");
  await screen.getByRole("button", "Link", { exact: true }).tap();
  await browser.evaluate(() => window.linkHold.requested.then(() => null));
  await open();
  await app.screenshot("09-repeat-open-during-current-submission");
  const currentReply = await browser.evaluate(() => window.linkHold.release());
  await app.screenshot("10-current-submission-closes-own-opening");
  results.currentReplyClosesOpening = currentReply === "Success" && !(await dialog.isVisible());
  await open();
  await input.fill("#999");
  await browser.keyboard.press("Control+Shift+n");
  await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 700)));
  await app.screenshot("11-new-thread-closes-dialog");
  results.newThreadCloses = !(await dialog.isVisible());
  expect(results).toEqual({ closesOnLeave: true, returnDoesNotReopen: true, reopensEmpty: true, secondOpenKeepsInput: true, oldReplyKeepsNewOpening: true, currentReplyClosesOpening: true, newThreadCloses: true, pullRequestsReturnDoesNotReopen: true });
});
