/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";

import { T3_HOME } from "../e2e.config.ts";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const decodePairing = Schema.decodeEffect(
  Schema.fromJsonString(Schema.Struct({ credential: Schema.String })),
);

const linkEnvironments = Effect.fn("scenario.linkEnvironments")(function* (
  primaryOrigin: string,
  secondOrigin: string,
  fallback: string,
) {
  const primary = yield* rpcClient(T3_HOME, primaryOrigin);
  const second = yield* rpcClient(SECOND_HOME, secondOrigin);
  for (const client of [primary, second]) {
    yield* client["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } });
  }
  const pairing = yield* makeState(SECOND_HOME).cli(["auth", "pairing", "create", "--json"]);
  const { credential } = yield* decodePairing(pairing.stdout);
  yield* primary["peerLinks.link"]({
    url: secondOrigin,
    alternateUrls: [fallback],
    pairingCode: credential,
    access: "full-access",
  });
}, Effect.scoped);

test(
  "Closing a linked thread tab during pairing keeps the current conversation",
  WEB,
  async ({ t3, app, browser, screen }) => {
    const project = await t3.project("primary");
    const current = await t3.thread({ project, title: "Current conversation", messages: ["first"] });
    const primary = app.baseUrl ?? "";
    const server = startSecondServer(primary);
    const requested = Promise.withResolvers<void>();
    const release = Promise.withResolvers<void>();
    try {
      const { host } = await server.ready;
      await runPromise(linkEnvironments(primary, host, host));
      const second = makeState(SECOND_HOME).state;
      const linkedProject = await second.project("linked");
      const remote = await second.thread({ project: linkedProject, title: "Remote delegated work", messages: ["second"] });
      const via = await runPromise(environmentId(primary));
      const target = await runPromise(environmentId(host));
      await t3.open(current);
      await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
      await browser.evaluate(async ({ via, target, currentId, remoteId }) => {
        const { useRightPanelStore } = await import("/src/rightPanelStore.ts");
        useRightPanelStore.getState().openLinkedThread(
          { environmentId: via, threadId: currentId },
          { viaEnvironmentId: via, environmentId: target, threadId: remoteId, label: "Scenario", title: "Remote delegated work" },
        );
      }, { via, target, currentId: current.threadId, remoteId: remote.threadId });
      await screen.getByRole("button", "Connect to interact").waitFor();
      await app.screenshot("1-read-only-linked-tab");
      await browser.route(`${host}/oauth/token`, async (route) => {
        requested.resolve();
        await release.promise;
        await route.continue();
      });
      await screen.getByRole("button", "Connect to interact").tap();
      await requested.promise;
      await screen.getByRole("button", "Close Remote delegated work", { exact: true }).tap();
      await app.screenshot("2-tab-closed-pairing-pending");
      release.resolve();
      // Wait for the real direct connection and its persisted catalog entry before judging navigation.
      await expect.poll(() => browser.evaluate(async (id) => {
        const { environmentCatalog } = await import("/src/connection/catalog.ts");
        const { appAtomRegistry } = await import("/src/rpc/atomRegistry.ts");
        return appAtomRegistry.get(environmentCatalog.catalogValueAtom).entries.has(id);
      }, target)).toBe(true);
      await screen.getByRole("button", "Connect to interact").waitFor({ state: "hidden" });
      // The catalog is saved before connect resolves; a round trip lets its navigation settle.
      await browser.evaluate(() => new Promise<void>((resolve) => setTimeout(resolve, 1000)));
      await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
      await app.screenshot("3-pairing-finished");
      expect(await browser.evaluate(() => decodeURIComponent(location.pathname))).toBe(`/${via}/${current.threadId}`);
    } finally {
      release.resolve();
      await server.stop();
    }
  },
);
