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

test("Try again renews an expired attachment PDF link", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("demo");
  const thread = await t3.thread({project, title: "PDF planning", messages: ["first"], model: "default"});
  await browser.addInitScript(() => {
    Object.defineProperty(navigator, "pdfViewerEnabled", {get: () => false});
    const original = window.fetch.bind(window);
    let expired: string | undefined;
    window.fetch = async (input, init) => {
      const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
      if (new URL(url, location.origin).pathname.startsWith("/api/assets/") && (init?.method ?? "GET") === "GET") {
        expired ??= url;
        if (url === expired) return new Response("Expired attachment link", {status: 403});
      }
      return original(input, init);
    };
  });
  await t3.open(thread);
  await screen.getByRole("textbox").waitFor();
  const editor = screen.getByRole("textbox");
  await editor.fill("Review this planning PDF");
  await browser.evaluate(() => {
    const objects = ["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Count 3 /Kids [3 0 R 5 0 R 7 0 R] >>"];
    for (const title of ["Page one", "Page two", "Page three"]) {
      const content = `BT /F1 24 Tf 50 700 Td (${title}) Tj ET`;
      const id = objects.length + 1;
      objects.push(`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 9 0 R >> >> /Contents ${id+1} 0 R >>`, `<< /Length ${content.length} >>\nstream\n${content}\nendstream`);
    }
    objects.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>");
    let pdf = "%PDF-1.4\n";
    const offsets = [0];
    objects.forEach((o,i) => {offsets.push(pdf.length); pdf += `${i+1} 0 obj\n${o}\nendobj\n`;});
    const xref = pdf.length;
    pdf += `xref\n0 ${objects.length+1}\n0000000000 65535 f \n${offsets.slice(1).map(o=>`${String(o).padStart(10,"0")} 00000 n \n`).join("")}trailer\n<< /Size ${objects.length+1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF`;
    const clipboardData = new DataTransfer();
    clipboardData.items.add(new File([pdf], "planning.pdf", {type:"application/pdf"}));
    document.querySelector('[contenteditable="true"]')!.dispatchEvent(new ClipboardEvent("paste", {clipboardData, bubbles:true, cancelable:true}));
  });
  await screen.getByRole("button", /File attachment, planning.pdf/).waitFor();
  await editor.press("ControlOrMeta+s");
  await browser.locator('[data-prompt-stash-badge="true"]').tap();
  await screen.getByRole("button", /^Restore stashed prompt:/).tap();
  await screen.getByRole("button", /File attachment, planning.pdf/).tap();
  await screen.getByRole("button", "Try again", {exact:true}).waitFor();
  await app.screenshot("expired-link");
  await screen.getByRole("button", "Try again", {exact:true}).tap();
  try {
    await expect(screen.getByText("1 / 3 pages", {exact:true})).toBeVisible({timeout:10000});
  } finally {
    await app.screenshot("after-try-again");
  }
});
