/// <reference lib="dom" />
import * as fs from "node:fs/promises";
import * as path from "node:path";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { sweepStalePendingAttachments } from "../../apps/server/src/attachmentStore.ts";
import { test, WEB } from "./t3.ts";

test("Restoring two expired report files leaves no dead chip after reattachment", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("reports");
  const thread = await t3.thread({project, title: "Report review", messages: ["Start"], model: "default"});
  await t3.open(thread);
  const composer = screen.getByRole("textbox");
  const attach = async () => {
    const uploaded = browser.waitForResponse(/\/api\/attachments\/upload\//, {timeout:15000});
    await browser.evaluate(() => {
      const input = document.querySelector<HTMLInputElement>('input[type="file"][multiple]');
      if (!input) throw new Error("Attachment input missing");
      const data = new DataTransfer();
      data.items.add(new File(['%PDF-1.4\n' + 'Synthetic report\n'.repeat(60)], 'report.pdf', {type:'application/pdf'}));
      input.files = data.files;
      input.dispatchEvent(new Event('change', {bubbles:true}));
      return null;
    });
    await uploaded;
    await screen.getByRole("button", /^File attachment, report.pdf/).waitFor();
    await screen.getByRole("button", "Submit message", {exact:true}).waitFor();
  };
  await composer.fill("First prompt about the report");
  await attach();
  await composer.press("ControlOrMeta+s");
  await screen.getByRole("button", /Stashed prompts: 1/).waitFor();
  await composer.fill("Second prompt, same report");
  await attach();
  await composer.press("ControlOrMeta+s");
  await screen.getByRole("button", /Stashed prompts: 2/).waitFor();
  const directory = path.join(T3_HOME, 'userdata', 'attachments');
  const old = new Date(Date.now() - 25 * 60 * 60 * 1000);
  for (const name of await fs.readdir(directory)) {
    if (name.startsWith('pending-')) await fs.utimes(path.join(directory, name), old, old);
  }
  const swept = sweepStalePendingAttachments({attachmentsDir: directory, nowMs:Date.now()});
  if (swept.deleted < 2) throw new Error(`Expected two expired uploads, swept ${swept.deleted}`);
  await t3.open(thread);
  await screen.getByRole("button", /Stashed prompts: 2/).tap();
  await screen.getByRole("button", /^Restore stashed prompt: First prompt/).tap();
  await screen.getByText(/stashed files are kept for 24 hours/, {exact:false}).waitFor();
  await screen.getByRole("button", /Stashed prompts: 1/).tap();
  await screen.getByRole("button", /^Restore stashed prompt: Second prompt/).tap();
  await composer.getByText("Second prompt, same report", {exact:false}).waitFor();
  await browser.evaluate(() => {
    document.querySelectorAll<HTMLButtonElement>('[aria-label="Dismiss notification"]').forEach(button => button.click());
    return null;
  });
  await screen.getByRole("button", "Dismiss notification").first().waitFor({state:"hidden"});
  await app.screenshot("two-expired-prompts-restored");
  await attach();
  await app.screenshot("report-reattached");
  await expect(browser.locator('[aria-label="Unavailable context, report.pdf"]')).toHaveCount(0);
});
