import test from "node:test";
import assert from "node:assert/strict";

import {
  isPageClosedError,
  normalizeImageCandidates,
  runWithOperationTimeout,
} from "./real-estate-photo-common.js";

test("normalizeImageCandidates keeps distinct Zillow photo URLs and strips query strings", () => {
  const result = normalizeImageCandidates(
    [
      {
        url: "https://photos.zillowstatic.com/fp/abc123-p_e.jpg?set=1",
        width: 1024,
        height: 768,
      },
      {
        url: "https://photos.zillowstatic.com/fp/abc123-p_e.jpg?set=2",
        width: 1024,
        height: 768,
      },
      {
        url: "https://www.zillow.com/static/logo.png",
        width: 120,
        height: 40,
      },
    ],
    {
      hostIncludes: ["photos.zillowstatic.com"],
      minWidth: 240,
      minHeight: 180,
    }
  );

  assert.deepEqual(result.map((item) => item.url), [
    "https://photos.zillowstatic.com/fp/abc123-p_e.jpg",
  ]);
});

test("normalizeImageCandidates filters tiny HAR page assets and keeps large photos", () => {
  const result = normalizeImageCandidates(
    [
      {
        url: "https://photos.har.com/123/main.jpg?size=large",
        width: 1600,
        height: 1200,
      },
      {
        url: "https://cdn.har.com/icons/close.svg",
        width: 24,
        height: 24,
      },
      {
        url: "data:image/png;base64,deadbeef",
        width: 800,
        height: 600,
      },
    ],
    {
      hostExcludes: ["doubleclick", "gstatic"],
      minWidth: 240,
      minHeight: 180,
    }
  );

  assert.deepEqual(result.map((item) => item.url), [
    "https://photos.har.com/123/main.jpg",
  ]);
});

test("runWithOperationTimeout rejects stalled work and runs timeout cleanup", async () => {
  let cleanedUp = false;

  await assert.rejects(
    async () =>
      runWithOperationTimeout(
        "HAR photo extraction",
        async () => await new Promise(() => {}),
        {
          timeoutMs: 20,
          onTimeout: async () => {
            cleanedUp = true;
          },
        }
      ),
    /timed out/i
  );

  assert.equal(cleanedUp, true);
});

test("isPageClosedError detects transient browser-session closure errors", () => {
  assert.equal(
    isPageClosedError(new Error("page.evaluate: Target page, context or browser has been closed")),
    true
  );
  assert.equal(
    isPageClosedError(new Error("Execution context was destroyed, most likely because of a navigation")),
    true
  );
  assert.equal(isPageClosedError(new Error("No Zillow image URLs were found")), false);
});
