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

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

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

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

  it("most offers pass schema validation", () => {
    const valid = offers.filter((o) => OfferSchema.safeParse(o).success);
    expect(valid.length).toBeGreaterThanOrEqual(20);
  });

  it("parses the exact MANN match correctly", () => {
    const mann = offers.find((o) => o.brand === "Mann-Filter");
    expect(mann).toBeDefined();
    expect(mann!.partNumber).toBe("W 712/52");
    expect(mann!.priceEur).toBe(5.99);
    expect(mann!.title).toBe("Eļļas filtrs");
    expect(mann!.availability).toBe("Pieejams");
    expect(mann!.url).toContain("https://www.xparts.lv/carparts/product/Mann-Filter/");
  });

  it("extracts the product image on every card", () => {
    for (const o of offers) expect(o.imageUrl).toMatch(/^https:\/\/xparts\.lv\/carparts\/img\//);
  });

  it("extracts spec attributes from the listing", () => {
    const mann = offers.find((o) => o.brand === "Mann-Filter")!;
    expect(mann.attributes).toContainEqual({ label: "Augstums", value: "92 mm" });
    expect(mann.attributes).toContainEqual({ label: "Filtra izpildījums", value: "Uzskrūvējams filtrs" });
    // Flag-style row without a value lands in value with an empty label
    expect(mann.attributes).toContainEqual({ label: "", value: "Ar atgriezējvārstu" });
  });

  it("keeps the separator between multi-value attributes", () => {
    const comline = offers.find((o) => o.partNumber === "EOF061")!;
    expect(comline.attributes).toContainEqual({ label: "Augstums", value: "93 mm, 92 mm" });
  });
});
