/// <reference lib="dom" />
import { expect } from "e2e";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { environmentId, makeState, runPromise, test, WEB } from "./t3.ts";

test("Disconnect completion preserves a chat opened on another server", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Local project");
  const local = await t3.thread({ project, title: "Local work", messages: ["Local work: keep this conversation open"] });
  const server = startSecondServer(app.baseUrl ?? "");
  try {
    const { host, token } = await server.ready;
    const second = makeState(SECOND_HOME);
    const remoteProject = await second.state.project("Remote project");
    const remote = await second.state.thread({ project: remoteProject, title: "Remote work", messages: ["Remote work"] });
    await t3.open("/settings/connections");
    await screen.getByRole("button", "Add environment").tap();
    const dialog = screen.getByRole("dialog", "Add Environment", { exact: true });
    await dialog.getByPlaceholder("backend.example.com").fill(host);
    await dialog.getByPlaceholder("PAIRCODE").fill(token);
    await dialog.getByRole("button", "Add environment").tap();
    await dialog.waitFor({ state: "hidden" });
    const remoteId = await runPromise(environmentId(host));
    await t3.open(`/${remoteId}/${remote.threadId}`);
    await screen.getByRole("textbox").waitFor();
    await server.stop();
    const disconnect = screen.getByRole("button", "Disconnect server");
    await disconnect.waitFor({ timeout: 60_000 });
    await browser.evaluate(() => {
      const original = IDBTransaction.prototype.addEventListener;
      let held = false;
      IDBTransaction.prototype.addEventListener = function(type, listener, options) {
        if (!held && type === "complete" && this.mode === "readwrite" && this.objectStoreNames.contains("catalog") && typeof listener === "function") {
          held = true;
          return original.call(this, type, (event) => {
            document.documentElement.dataset.disconnectHeld = "true";
            document.addEventListener("release-disconnect", () => {
              listener.call(this, event);
              document.documentElement.dataset.disconnectReleased = "true";
            }, { once: true });
          }, options);
        }
        return original.call(this, type, listener, options);
      } as typeof IDBTransaction.prototype.addEventListener;
      return null;
    });
    await disconnect.tap();
    await browser.locator('html[data-disconnect-held="true"]').waitFor();
    await browser.locator(`[data-thread-item$="${local.threadId}"]`).tap();
    await screen.getByText("Local work: keep this conversation open", { exact: true }).waitFor();
    await app.screenshot("local-chat-while-disconnect-pending");
    await browser.evaluate(() => { document.dispatchEvent(new Event("release-disconnect")); return null; });
    await browser.locator('html[data-disconnect-released="true"]').waitFor();
    await browser.locator(`[data-thread-item$="${remote.threadId}"]`).waitFor({ state: "hidden" });
    await browser.evaluate(() => new Promise<null>((resolve) => setTimeout(() => resolve(null), 1000)));
    try {
      await expect(screen.getByText("Local work: keep this conversation open", { exact: true })).toBeVisible();
    } finally {
      await app.screenshot("after-disconnect-completes");
    }
  } finally { await server.stop(); }
});
