/**
 * `useObjectUrls` — the one remaining `react-hooks/set-state-in-effect` report
 * that is a genuine external-resource synchronisation rather than a read of a
 * browser-only value.
 *
 * The report is documented in place as an unresolved exception. What that
 * documentation claims is that the effect's cleanup is correct, so that is
 * what is asserted here: every URL this hook creates is revoked, across a
 * file-list change, StrictMode's double mount, and unmount. A leak is
 * invisible in a browser — the page just holds the blob until it closes — so
 * the only way to know is to count.
 */
import { beforeEach, test } from "node:test";
import assert from "node:assert/strict";

import { installDom, renderHook } from "./reactHarness";
import { useObjectUrls } from "@/components/ui/useObjectUrls";

interface UrlLedger {
  created: string[];
  revoked: string[];
  outstanding(): string[];
}

/**
 * jsdom implements `URL.createObjectURL` as a stub that throws, so the two
 * calls are recorded instead. That is the right level anyway: what is being
 * checked is the pairing, not the browser's blob table.
 */
function trackObjectUrls(): UrlLedger {
  const created: string[] = [];
  const revoked: string[] = [];
  let next = 0;
  const url = globalThis.URL as unknown as {
    createObjectURL: (file: unknown) => string;
    revokeObjectURL: (value: string) => void;
  };
  url.createObjectURL = () => {
    const value = `blob:fursa/${next++}`;
    created.push(value);
    return value;
  };
  url.revokeObjectURL = (value: string) => void revoked.push(value);
  return {
    created,
    revoked,
    outstanding: () => created.filter((value) => !revoked.includes(value)),
  };
}

const fileNamed = (name: string) =>
  ({ name, size: 1, type: "image/png" }) as unknown as File;

let ledger: UrlLedger;
beforeEach(() => {
  installDom();
  ledger = trackObjectUrls();
});

test("creates one URL per file and exposes them in order", () => {
  const files = [fileNamed("a.png"), fileNamed("b.png")];
  const probe = renderHook(() => useObjectUrls(files));
  probe.mount();

  assert.deepEqual(probe.last(), ledger.created);
  assert.equal(ledger.created.length, 2);
});

test("revokes everything on unmount", () => {
  const files = [fileNamed("a.png"), fileNamed("b.png")];
  const probe = renderHook(() => useObjectUrls(files));
  probe.mount();
  probe.unmount();

  assert.deepEqual(ledger.outstanding(), []);
});

test("revokes the previous set when the file list changes", () => {
  let files = [fileNamed("a.png")];
  const probe = renderHook(() => useObjectUrls(files));
  probe.mount();
  const first = [...ledger.created];

  // A re-pick hands the hook a new array — the caller's state, so a new identity.
  files = [fileNamed("a.png"), fileNamed("b.png")];
  probe.rerender();

  assert.deepEqual(
    first.filter((url) => !ledger.revoked.includes(url)),
    [],
    "the superseded preview must not outlive the pick that replaced it"
  );
  assert.deepEqual(probe.last(), ledger.created.slice(first.length));

  probe.unmount();
  assert.deepEqual(ledger.outstanding(), []);
});

test("leaks nothing under StrictMode's double effect invocation", () => {
  const files = [fileNamed("a.png"), fileNamed("b.png")];
  const probe = renderHook(() => useObjectUrls(files), { strict: true });
  probe.mount();

  /* The reason this hook is an effect and not a `useMemo`: StrictMode
     allocates twice, and only an effect's cleanup is guaranteed to run for the
     discarded set. The second pass's URLs are the live ones. */
  assert.equal(ledger.created.length, 4);
  assert.deepEqual(ledger.outstanding(), probe.last());
  assert.equal((probe.last() as string[]).length, 2);

  probe.unmount();
  assert.deepEqual(ledger.outstanding(), []);
});

test("an empty file list allocates nothing", () => {
  /* Hoisted, not inline. An array literal in the call expression is a new
     identity every render, so the effect would re-run, publish a new array,
     and re-render for ever — the identity requirement in the hook's note is
     load-bearing, and this is what violating it looks like. */
  const none: File[] = [];
  const probe = renderHook(() => useObjectUrls(none));
  probe.mount();

  assert.deepEqual(probe.last(), []);
  assert.equal(ledger.created.length, 0);
});
