/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

declare global { interface Window { stashHoldEnabled?: boolean; stashVerify: { requested: Promise<void>; release: () => Promise<void> }; } }

test("Leaving during file verification keeps the saved prompt restorable", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("server");
  const thread = await t3.thread({project, title: "Reproduction Hello", messages: ["first"], model: "default"});
  await browser.addInitScript(() => {
    const requested = Promise.withResolvers<void>();
    const replied = Promise.withResolvers<void>();
    let release = () => {};
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      if (!window.stashHoldEnabled || typeof data !== "string" || !data.includes('assets.createUrl')) return send.call(this, data);
      const parsed = JSON.parse(data);
      const frames = [parsed].flat();
      const held = frames.filter(frame => frame.tag === "assets.createUrl");
      if (!held.length) return send.call(this, data);
      const others = frames.filter(frame => frame.tag !== "assets.createUrl");
      if (others.length) send.call(this, JSON.stringify(others));
      this.addEventListener("message", event => {
        if ([JSON.parse(String(event.data))].flat().some(frame => frame._tag === "Exit" && String(frame.requestId) === String(held[0].id))) replied.resolve();
      });
      release = () => send.call(this, Array.isArray(parsed) ? JSON.stringify(held) : data);
      requested.resolve();
    };
    window.stashVerify = {requested: requested.promise, release: async () => { window.stashHoldEnabled = false; release(); await replied.promise; await new Promise(resolve => setTimeout(resolve, 500)); }};
  });
  await t3.open(thread);
  const composer = screen.getByRole("textbox");
  await composer.fill("Review these notes please");
  await browser.evaluate(() => {
    const input = document.querySelector<HTMLInputElement>('input[type="file"][multiple]')!;
    const transfer = new DataTransfer();
    transfer.items.add(new File(["Synthetic review notes."], "notes.txt", {type:"text/plain"}));
    input.files = transfer.files;
    input.dispatchEvent(new Event("change", {bubbles:true}));
  });
  await screen.getByRole("button", /File attachment, notes.txt/).waitFor();
  // Wait for the real upload to finish before saving it.
  await browser.evaluate(async () => {
    while (document.body.textContent?.includes("Uploading")) await new Promise(resolve => requestAnimationFrame(resolve));
  });
  await composer.press("ControlOrMeta+s");
  const stash = screen.getByRole("button", /Stashed prompts: 1/);
  await stash.waitFor();
  await t3.open(thread);
  await browser.evaluate(() => { window.stashHoldEnabled = true; });
  await stash.tap();
  await screen.getByRole("button", /Restore stashed prompt: Review these notes please/).tap();
  await browser.evaluate(async () => { await window.stashVerify.requested; });
  await screen.getByRole("button", "New thread in server", {exact:true}).first().tap();
  await browser.evaluate(async () => { await window.stashVerify.release(); });
  await app.screenshot("new-composer-after-verification");
  await expect(stash).toBeVisible();
  await stash.tap();
  await screen.getByRole("button", /Restore stashed prompt: Review these notes please/).tap();
  await expect(composer).toHaveText(/Review these notes please/);
  await expect(screen.getByRole("button", /File attachment, notes.txt/)).toBeVisible();
  await screen.getByText("0%", {exact:true}).waitFor({state:"hidden"});
  await app.screenshot("saved-prompt-restored-in-new-composer");
});
