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

test("Stashing a failed upload tells the user to retry or remove it", WEB, async ({ t3, app, browser, screen }) => {
  await browser.setViewport({ width: 1440, height: 900 });
  await t3.project("demo");
  await t3.open();
  const composer = screen.getByRole("textbox");
  await composer.fill("Summarize these notes");
  await browser.route(/\/api\/attachments\/upload\//, (route) => route.abort());
  await browser.evaluate(() => {
    const input = document.querySelector('input[type="file"]');
    if (!(input instanceof HTMLInputElement)) throw new Error("File input missing");
    const transfer = new DataTransfer();
    transfer.items.add(new File(["These are sample notes.\nx"], "notes.txt", { type: "text/plain" }));
    input.files = transfer.files;
    input.dispatchEvent(new Event("change", { bubbles: true }));
    return null;
  });
  await screen.getByText("upload failed", { exact: true }).waitFor();
  await composer.tap();
  await browser.keyboard.press("Control+s");
  await screen.getByText(/before stashing this prompt/).waitFor();
  // Let the toast entry transition settle before capturing its full message.
  await browser.evaluate(() => new Promise((resolve) => setTimeout(() => resolve(null), 1000)));
  await app.screenshot("failed-upload-stash-toast");
  await expect(screen.getByText(/before stashing this prompt/)).toHaveText("Retry or remove failed file uploads before stashing this prompt");
  await expect(composer).toContainText("Summarize these notes");
  await expect(screen.getByText("upload failed", { exact: true })).toBeVisible();
  const stashes = await browser.evaluate(() => Object.entries(localStorage).filter(([key]) => /stash/i.test(key)));
  expect(stashes).toEqual([]);
});
