/// <reference lib="dom" />
import { execFileSync } from "node:child_process";
import { T3_HOME } from "../e2e.config.ts";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Archived and deleted threads refuse resent message commands", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("Resend demonstration");
  const results: string[] = [];
  for (const lifecycle of ["archive", "delete"]) {
  const thread = await t3.thread({project, title: `${lifecycle} resend demonstration`, messages: ["Start"]});
  await t3.open(thread);
  const snapshot = () => JSON.parse(execFileSync("sqlite3", ["-readonly", "-json", `${T3_HOME}/userdata/statev2.sqlite`, `SELECT t.archived_at IS NOT NULL AS archived, t.deleted_at IS NOT NULL AS deleted, (SELECT count(*) FROM orchestration_v2_projection_runs r WHERE r.thread_id=t.thread_id) AS runs, (SELECT status FROM orchestration_v2_projection_runs r WHERE r.thread_id=t.thread_id ORDER BY ordinal DESC LIMIT 1) AS latestStatus FROM orchestration_v2_projection_threads t WHERE thread_id='${thread.threadId.replaceAll("'", "''")}';`], {encoding:"utf8"}))[0];
  await browser.evaluate(() => {
    const send = WebSocket.prototype.send;
    (window as any).resendProof = {};
    WebSocket.prototype.send = function(data) {
      if(typeof data === "string") {
        try {
          for(const frame of [JSON.parse(data)].flat()) {
            if(frame.tag === "orchestration.dispatchCommand" && JSON.stringify(frame).includes('message.dispatch')) {
              (window as any).resendProof = { socket: this, frame, send };
            }
          }
        } catch {}
      }
      return send.call(this, data);
    };
  });
  await screen.getByRole("textbox").fill("Normal message before archive");
  await screen.getByRole("textbox").press("Enter");
  await screen.getByText("second fixture turn complete", {exact:false}).waitFor();
  await screen.getByRole("button", "Stop generation").waitFor({state:"hidden"});
  const before = snapshot();
  await screen.getByRole("button", `Thread actions for ${lifecycle} resend demonstration`).tap();
  await screen.getByRole("menuitem", lifecycle === "archive" ? "Archive thread" : "Delete", {exact:true}).tap();
  if(lifecycle === "delete") await screen.getByRole("button", "Confirm", {exact:true}).tap();
  await screen.getByRole("button", `Thread actions for ${lifecycle} resend demonstration`).waitFor({state:"hidden"});
  const outcome = await browser.evaluate(async () => {
    const proof = (window as any).resendProof;
    const frame = structuredClone(proof.frame);
    frame.id = String(900001);
    const replace = (value: any) => {
      if(!value || typeof value !== "object") return;
      if(value.type === "message.dispatch") {
        value.commandId = crypto.randomUUID(); value.messageId = crypto.randomUUID(); value.text = "sent after archive";
      }
      for(const item of Object.values(value)) replace(item);
    };
    replace(frame);
    const response = await new Promise<any>((resolve) => {
      const listener = (event: MessageEvent) => {
        for(const item of [JSON.parse(event.data)].flat()) {
          if(String(item.requestId) === frame.id && item._tag === "Exit") { proof.socket.removeEventListener("message", listener); resolve(item); }
        }
      };
      proof.socket.addEventListener("message", listener);
      proof.send.call(proof.socket, JSON.stringify(frame));
    });
    const exit = response.exit ?? response;
    return {status: exit._tag, message: exit.cause?.[0]?.error?.message ?? "", sequence: exit.value?.sequence ?? null};
  });
  if(outcome.status === "Success") {
    await expect.poll(() => snapshot().latestStatus).toBe("completed");
  }
  const after = snapshot();
  await browser.evaluate(({lifecycle, outcome, before, after}) => {
    document.getElementById("resend-proof-panel")?.remove();
    const panel = document.createElement("section");
    panel.id = "resend-proof-panel";
    panel.style.cssText = "position:fixed;inset:110px 60px auto;z-index:99999;background:#111827;color:#f9fafb;padding:28px;border:2px solid #64748b;border-radius:12px;font:18px/1.6 monospace;white-space:pre-wrap";
    panel.textContent = `${lifecycle.toUpperCase()} — LIVE WEBSOCKET RESEND

Normal composer message completed.
Thread hidden through Thread actions > ${lifecycle}.
Captured message.dispatch resent with fresh IDs.

Actual server reply: ${outcome.status}
${outcome.message ? outcome.message.replace(/mcp:[a-f0-9-]+/g, "[thread]") : "Committed at sequence " + outcome.sequence}

Read-only snapshot of this isolated app's persisted state:
Provider runs before resend: ${before.runs}
Provider runs after resend:  ${after.runs}
Latest run status: ${after.latestStatus}
Still ${lifecycle === "archive" ? "archived: " + Boolean(after.archived) : "deleted: " + Boolean(after.deleted)}`;
    document.body.append(panel);
    return null;
  }, {lifecycle, outcome, before, after});
  await app.screenshot(`${lifecycle}-resend-server-and-runs`);
  results.push(outcome.status);
  await browser.evaluate(() => { document.getElementById("resend-proof-panel")?.remove(); return null; });
  }
  expect(results, "Hidden threads must reject both resends").toEqual(["Failure", "Failure"]);
});
