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

test("TSV final record respects the one MiB limit", WEB, async ({ t3, app, browser, screen }) => {
  const limit = 1024 * 1024;
  const project = await t3.project("tsv-record-limit", {
    "at-limit-nolf.tsv": "a".repeat(limit),
    "at-limit-lf.tsv": "a".repeat(limit) + "\n",
    "over-nolf.tsv": "a".repeat(limit + 1),
    "over-lf.tsv": "a".repeat(limit + 1) + "\n",
  });
  const thread = await t3.thread({ project, title: "TSV record size boundary", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByText("fixture turn complete", { exact: false }).waitFor();
  const results: Record<string, unknown> = {};
  for (const file of ["at-limit-nolf.tsv", "at-limit-lf.tsv", "over-lf.tsv", "over-nolf.tsv"]) {
    await browser.keyboard.press("Control+p");
    await screen.getByPlaceholder("Search files…").fill(file);
    await screen.getByRole("option", file, { exact: false }).tap();
    await screen.getByText(/(?:0 rows|A line or record exceeds)/).waitFor();
    await app.screenshot(file.replace(".tsv", ""));
    results[file] = await browser.evaluate(() => {
      const error = document.body.innerText.includes("A line or record exceeds the 1 MB preview limit.");
      const lengths = [...document.querySelectorAll("th, [role=columnheader]")].map(el => el.textContent?.length ?? 0);
      return error ? "size-limit error" : Math.max(0, ...lengths);
    });
    await browser.keyboard.press("Escape");
  }
  await expect(results).toEqual({
    "at-limit-nolf.tsv": limit,
    "at-limit-lf.tsv": limit,
    "over-lf.tsv": "size-limit error",
    "over-nolf.tsv": "size-limit error",
  });
});
