import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import { CommandId, ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as Effect from "effect/Effect";

import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

// A shell keeps an environment's 25 newest settled threads; older ones are paged in.
const NEWER_SETTLED = 25;

const uuid = Effect.flatMap(SecureRandom.SecureRandom, (random) => random.uuidV4());

const settle = Effect.fn("scenario.settle")(
  function* (origin: string, threadIds: ReadonlyArray<string>) {
    const client = yield* rpcClient(T3_HOME, origin);
    for (const threadId of threadIds) {
      yield* client["orchestration.dispatchCommand"]({
        type: "thread.settle",
        commandId: CommandId.make(yield* uuid),
        threadId: ThreadId.make(threadId),
      });
    }
  },
  Effect.scoped,
  Effect.provide(NodeCrypto.layer),
);

test(
  "Reopen Closed Tab returns to a tab of an older settled thread",
  WEB,
  async ({ t3, app, browser, screen }) => {
    const project = await t3.project("demo");
    const ancient = await t3.thread({
      project,
      title: "Ancient design notes",
      messages: ["Ancient work"],
    });
    const newer = [];
    for (let index = 1; index <= NEWER_SETTLED; index++) {
      newer.push(await t3.thread({ project, title: `Newer ${index}`, messages: ["first"] }));
    }
    // Settled first, so the newer ones push it out of the shell.
    await runPromise(
      settle(app.baseUrl ?? "", [ancient.threadId, ...newer.map((thread) => thread.threadId)]),
    );

    await t3.open(ancient);
    await screen.getByText("Ancient work", { exact: true }).waitFor();
    await screen.getByRole("button", "Toggle right panel", { exact: true }).tap();
    await screen.getByRole("button", "Files F", { exact: true }).tap();
    const closeFiles = screen.getByRole("button", "Close Files", { exact: true });
    await closeFiles.tap();
    await closeFiles.waitFor({ state: "hidden" });

    await t3.open(newer.at(-1)!);
    await screen.getByText("first", { exact: true }).waitFor();
    // Stands in for a shell cache past its 12-hour resume limit (or a server update): the next
    // load takes a fresh snapshot, which leaves the older settled thread out, while the closed
    // tab history survives in local storage.
    await browser.evaluate(
      () =>
        new Promise<void>((resolve, reject) => {
          const open = indexedDB.open("t3code:connection-runtime");
          open.onerror = () => reject(open.error);
          open.onsuccess = () => {
            const tx = open.result.transaction("shell", "readwrite");
            tx.objectStore("shell").clear();
            tx.oncomplete = () => {
              open.result.close();
              resolve();
            };
            tx.onerror = () => reject(tx.error);
          };
        }),
    );
    await browser.reload();
    await screen.getByText("first", { exact: true }).waitFor();

    await browser.keyboard.press("ControlOrMeta+Shift+T");
    try {
      await expect(screen.getByText("Ancient work", { exact: true })).toBeVisible({
        timeout: 10_000,
      });
      await expect(closeFiles).toBeVisible();
    } finally {
      await app.screenshot("after-reopen-closed-tab");
    }
  },
);
