// src/lib/keywords/onpage-fetch.test.ts
import { describe, expect, it } from "bun:test";
import { fetchHtmlWith } from "./onpage-fetch";

function fakeResponse(
  body: string,
  init: { status?: number; type?: string } = {},
) {
  return new Response(body, {
    status: init.status ?? 200,
    headers: { "content-type": init.type ?? "text/html; charset=utf-8" },
  });
}

describe("fetchHtml", () => {
  it("200 HTML → texte", async () => {
    const f = fetchHtmlWith(async () => fakeResponse("<html>ok</html>"));
    expect(await f("https://ex.dev/")).toBe("<html>ok</html>");
  });
  it("non-200 → null", async () => {
    const f = fetchHtmlWith(async () => fakeResponse("nope", { status: 403 }));
    expect(await f("https://ex.dev/")).toBeNull();
  });
  it("content-type non HTML → null", async () => {
    const f = fetchHtmlWith(async () =>
      fakeResponse("{}", { type: "application/json" }),
    );
    expect(await f("https://ex.dev/")).toBeNull();
  });
  it("exception fetch → null", async () => {
    const f = fetchHtmlWith(async () => {
      throw new Error("boom");
    });
    expect(await f("https://ex.dev/")).toBeNull();
  });
  it("corps > cap → tronqué sans throw", async () => {
    const big = "x".repeat(4 * 1024 * 1024);
    const f = fetchHtmlWith(async () => fakeResponse(big));
    const out = await f("https://ex.dev/");
    expect(out).not.toBeNull();
    expect((out as string).length).toBeLessThanOrEqual(3 * 1024 * 1024);
  });
});
