// test/firecrawl-fetch.test.ts — fetchViaFirecrawl : adapte FirecrawlPage
// (scrapeOne, Task 1) à la signature attendue par le runner sémantique
// (`{ html: string; finalUrl: string } | null`, cf. analysis-runner.ts:75).
// `scrapeOne` est injecté (DI, pas de mock.module) — un fake suffit, pas
// besoin de réseau ni d'env Firecrawl configurée.
import { describe, expect, test } from "bun:test";
import type { FirecrawlPage } from "../src/firecrawl";
import { fetchViaFirecrawl } from "../src/firecrawl-fetch";

function fakeScrapeOne(page: FirecrawlPage): (url: string) => Promise<FirecrawlPage> {
  return async () => page;
}

describe("fetchViaFirecrawl", () => {
  test("status ok → { html, finalUrl: url } (finalUrl = URL demandée, pas post-redirect)", async () => {
    const url = "https://example.com/a";
    const scraper = fakeScrapeOne({
      url,
      html: "<html>content</html>",
      status: "ok",
      httpStatus: 200,
    });
    const result = await fetchViaFirecrawl(url, scraper);
    expect(result).toEqual({ html: "<html>content</html>", finalUrl: url });
  });

  test("status blocked → null (pas de throw)", async () => {
    const url = "https://example.com/blocked";
    const scraper = fakeScrapeOne({
      url,
      html: null,
      status: "blocked",
      httpStatus: 403,
    });
    expect(await fetchViaFirecrawl(url, scraper)).toBeNull();
  });

  test("status timeout → null (pas de throw)", async () => {
    const url = "https://example.com/slow";
    const scraper = fakeScrapeOne({ url, html: null, status: "timeout" });
    expect(await fetchViaFirecrawl(url, scraper)).toBeNull();
  });

  test("status empty → null (pas de throw)", async () => {
    const url = "https://example.com/empty";
    const scraper = fakeScrapeOne({
      url,
      html: "",
      status: "empty",
      httpStatus: 200,
    });
    expect(await fetchViaFirecrawl(url, scraper)).toBeNull();
  });

  test("status fetch_error → null (pas de throw)", async () => {
    const url = "https://example.com/error";
    const scraper = fakeScrapeOne({ url, html: null, status: "fetch_error" });
    expect(await fetchViaFirecrawl(url, scraper)).toBeNull();
  });

  test("status ok mais html null (défensif) → null", async () => {
    const url = "https://example.com/weird";
    const scraper = fakeScrapeOne({ url, html: null, status: "ok" });
    expect(await fetchViaFirecrawl(url, scraper)).toBeNull();
  });
});
