import { readFileSync } from "node:fs";
import { describe, expect, it, vi } from "vitest";
import { rd24 } from "../src/adapters/rd24.js";
import { normalizeQuery } from "../src/core/normalize.js";
import { OfferSchema, type FetchContext } from "../src/core/types.js";

const html = readFileSync("fixtures/rd24/W71252.html", "utf-8");

describe("rd24 adapter (fixture: W71252, recorded 2026-07-10)", () => {
  const offers = rd24.parse(html, normalizeQuery("W 712/52")!);

  it("finds the product cards", () => {
    expect(offers.length).toBe(15);
  });

  it("waits for a result card before accepting a rendered 403 page", async () => {
    const fetchPageHtml = vi.fn().mockResolvedValue(html);
    const ctx = { browser: { fetchPageHtml } } as unknown as FetchContext;

    await rd24.fetchRaw(normalizeQuery("W 712/52")!, ctx);

    expect(fetchPageHtml).toHaveBeenCalledWith(
      "rd24",
      "https://www.rezervesdalas24.lv/spares-search.html?keyword=W71252",
      { waitForSelector: ".listing [data-product-item]" },
    );
  });

  it("every offer passes schema validation", () => {
    for (const o of offers) expect(() => OfferSchema.parse(o)).not.toThrow();
  });

  it("parses the known MANN filter correctly", () => {
    const mann = offers.find((o) => o.partNumber === "W 712/52");
    expect(mann).toBeDefined();
    expect(mann!.brand).toBe("MANN-FILTER");
    expect(mann!.priceEur).toBe(8.24);
    expect(mann!.title).toContain("Eļļas filtrs");
    expect(mann!.availability).toBe("Ir noliktavā");
    expect(mann!.url).toBe("https://www.rezervesdalas24.lv/mann-filter-963592.html");
  });

  it("extracts image and spec attributes", () => {
    const mann = offers.find((o) => o.partNumber === "W 712/52")!;
    expect(mann.imageUrl).toBe("https://media.autoteiledirekt.de/360_photos/963592/preview.jpg");
    expect(mann.attributes).toContainEqual({ label: "Filtra izpildījums", value: "Uzskrūvējams filtrs" });
    expect(mann.attributes).toContainEqual({ label: "Augstums", value: "92" });
  });
});
