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

const canonicalize = (v: string): string => v.toUpperCase().replace(/[^A-Z0-9]/g, "");
const html = readFileSync("fixtures/ic24/W71252.html", "utf-8");

describe("ic24 adapter (fixture: W71252, recorded 2026-07-13 via resident browser warm session)", () => {
  const offers = ic24.parse(html, normalizeQuery("W71252")!);

  it("encodes search paths without a Node Buffer runtime", () => {
    expect(encodeIc24Search("W71252")).toBe("VzcxMjUy");
    expect(encodeIc24Search("A")).toBe("QQ==");
  });

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

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

  it("surfaces the searched MANN-FILTER part with its VAT-inclusive (gross) price", () => {
    const mann = offers.find((o) => canonicalize(o.partNumber) === "W71252");
    expect(mann).toBeDefined();
    expect(mann!.brand).toBe("MANN-FILTER");
    expect(mann!.partNumber).toBe("W 712/52");
    // Gross (6.76), NOT the hidden net price (5.59) — parity with the other stores.
    expect(mann!.priceEur).toBe(6.76);
    expect(mann!.url).toContain("/produkti/");
    expect(mann!.imageUrl).toContain("intercars");
  });

  it("reports availability as a stock quantity", () => {
    const mann = offers.find((o) => canonicalize(o.partNumber) === "W71252")!;
    expect(mann.availability).toMatch(/Pieejams \(\d+ gab\.\)/);
  });

  it("includes cross-brand analogues, each with its own part number and a positive price", () => {
    const brands = new Set(offers.map((o) => o.brand));
    expect(brands.size).toBeGreaterThan(1);
    for (const o of offers) expect(o.priceEur).toBeGreaterThan(0);
  });
});
