/// <reference lib="dom" />
import { CommandId, ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Settling skips the next thread deleted while saving", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Demo");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client.subscribeServerConfig({}).pipe(
      Stream.filter(event => {
        const providers = event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : [];
        return providers.some(p => p.instanceId === "devReplay" && p.models?.some(m => m.slug === "multi-turn"));
      }), Stream.runHead,
    );
  }).pipe(Effect.scoped, Effect.timeout("30 seconds")));
  const a = await t3.thread({ project, title: "Thread A", messages: ["Thread A is the remaining work."] });
  const b = await t3.thread({ project, title: "Thread B", messages: ["Thread B will be deleted."] });
  const c = await t3.thread({ project, title: "Thread C", messages: ["Thread C is ready to settle."] });
  await browser.setViewport({ width: 1440, height: 900 });
  await browser.addInitScript(() => {
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      if (typeof data === "string" && [JSON.parse(data)].flat().some(r => r.tag === "orchestration.dispatchCommand" && r.payload?.type === "thread.settle")) {
        document.documentElement.dataset.settleHeld = "yes";
        document.addEventListener("release-settle", () => send.call(this, data), { once: true });
        return;
      }
      return send.call(this, data);
    };
  });
  await t3.open(c);
  await screen.getByText("Thread C is ready to settle.", { exact: true }).waitFor();
  await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
  await app.screenshot("original-order-c-b-a");
  const row = browser.locator(`[data-sidebar-row$="${c.threadId}"]`);
  await row.hover();
  await row.getByRole("button", "Settle thread", { exact: true }).tap();
  await browser.locator('html[data-settle-held="yes"]').waitFor();
  await runPromise(Effect.gen(function*() {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["orchestration.dispatchCommand"]({ type: "thread.delete", commandId: CommandId.make(crypto.randomUUID()), threadId: ThreadId.make(b.threadId) });
  }).pipe(Effect.scoped));
  await browser.locator(`[data-sidebar-row$="${b.threadId}"]`).waitFor({ state: "hidden" });
  await browser.mouse.move(700, 500);
  await browser.locator('[data-slot="tooltip-popup"]').waitFor({ state: "hidden" });
  await app.screenshot("next-candidate-deleted-while-settle-held");
  await browser.evaluate(() => { document.dispatchEvent(new Event("release-settle")); return null; });
  await browser.waitForURL(new RegExp(`(/draft/|${encodeURIComponent(a.threadId)})`));
  // Both outcomes reach a stable composer: remaining thread on head, new draft on base.
  await browser.locator('[role="textbox"]').waitFor();
  await browser.locator('[data-slot="toast-description"]').waitFor({ state: "hidden" });
  await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
  await app.screenshot("destination-after-settle");
  await expect.poll(async () => decodeURIComponent(new URL(await browser.url()).pathname.split("/").at(-1) ?? "")).toBe(a.threadId);
});
