import { mkdir } from "node:fs/promises";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

// Every mutation goes through the running app's authenticated RPC, never database fixtures.
test("Settled counts follow a promoted scratch folder without reconnecting", WEB, async ({ t3, app, screen, browser }) => {
  const filler = await t3.project("Recent work");
  const landing = await t3.thread({ project: filler, title: "Current work", messages: ["Ready"] });
  await t3.open(landing);
  const rpc = async (operations: Array<{ tag: string; payload: unknown }>) => browser.evaluate(async (operations) => {
    const ticket = await (await fetch("/api/auth/websocket-ticket/rpc", { method: "POST" })).json();
    const ws = new WebSocket(`${location.origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=2&wsTicket=${encodeURIComponent(ticket.ticket)}`);
    await new Promise<void>((resolve, reject) => { ws.onopen = () => resolve(); ws.onerror = () => reject(new Error("RPC socket failed")); });
    let seq = 0;
    try {
      const results = [];
      for (const operation of operations) {
        const id = String(++seq);
        const result = await new Promise<any>((resolve, reject) => {
          ws.onmessage = (event) => {
            const messages = JSON.parse(event.data);
            for (const message of Array.isArray(messages) ? messages : [messages]) {
              if (message._tag === "Ping") ws.send(JSON.stringify({ _tag: "Pong" }));
              if (message._tag === "Exit" && message.requestId === id) {
                if (message.exit._tag === "Success") resolve(message.exit.value);
                else reject(new Error(JSON.stringify(message.exit)));
              }
            }
          };
          ws.send(JSON.stringify({ _tag: "Request", id, tag: operation.tag, payload: operation.payload, headers: [] }));
        });
        results.push(result);
      }
      return results;
    } finally { ws.close(); }
  }, operations);
  const [{ projectId: scratchId }] = await rpc([{ tag: "projects.ensureScratch", payload: {} }]);
  const shell = await browser.evaluate(async () => (await fetch("/api/orchestration/shell", { headers: { "x-t3-orchestration-protocol": "2" } })).json());
  const scratchRoot = shell.projects.find((p: any) => p.id === scratchId).workspaceRoot;
  const folder = `${scratchRoot}/promotion-demo`;
  await mkdir(folder, { recursive: true });
  const projectId = shell.projects.find((p: any) => p.title === "Recent work").id;
  const command = (payload: any) => ({ tag: "orchestration.dispatchCommand", payload: { commandId: crypto.randomUUID(), ...payload } });
  const create = (threadId: string, projectId: string, title: string, worktreePath: string | null) => command({ type: "thread.create", threadId, projectId, title, worktreePath, branch: null, modelSelection: { instanceId: "devReplay", model: "multi-turn" }, runtimeMode: "full-access", interactionMode: "default", createdBy: "user", creationSource: "web" });
  const old = crypto.randomUUID();
  const sibling = crypto.randomUUID();
  await rpc([create(old, scratchId, "Promoted notes", folder), command({ type: "thread.settle", threadId: old, settledAt: "2026-01-01T00:00:00.000Z" }), command({ type: "thread.pin", threadId: old }), create(sibling, scratchId, "Older folder notes", folder), command({ type: "thread.settle", threadId: sibling, settledAt: "2026-01-02T00:00:00.000Z" })]);
  const newer = Array.from({ length: 25 }, (_, index) => {
    const id = crypto.randomUUID();
    return [create(id, projectId, `Recent settled ${index + 1}`, null), command({ type: "thread.settle", threadId: id })];
  }).flat();
  await rpc(newer);
  // A fresh document reconnects after seeding, establishing the 25-thread settled window.
  await t3.open(landing);
  await screen.getByRole("combobox", "Filter threads by project", { exact: true }).tap();
  await screen.getByRole("option", "No project", { exact: false }).tap();
  await app.screenshot("scratch-before-promotion");
  await rpc([{ tag: "projects.createFromThread", payload: { threadId: old } }]);
  // Keep the scope on No project and allow the existing 500ms count debounce to finish.
  await browser.evaluate(() => new Promise((resolve) => setTimeout(resolve, 1800)));
  await app.screenshot("no-project-after-promotion");
  const noProjectCount = await browser.locator('[data-sidebar-row="shelf:settled"]').textContent();
  await screen.getByRole("combobox", "Filter threads by project: No project", { exact: true }).tap();
  await screen.getByRole("option", "Promoted notes", { exact: false }).tap();
  await app.screenshot("destination-after-promotion");
  const destinationCount = await browser.locator('[data-sidebar-row="shelf:settled"]').textContent();
  expect({ noProjectCount, destinationCount }).toEqual({ noProjectCount: "Settled0", destinationCount: "Settled1" });
});
