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

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

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

  it("finds the single exact match", () => {
    expect(offers.length).toBe(1);
  });

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

  it("takes the promo price, not the struck-through old price", () => {
    const o = offers[0]!;
    expect(o.brand).toBe("MANN-FILTER");
    expect(o.partNumber).toBe("W 712/52");
    expect(o.priceEur).toBe(5.42); // 6,78 € is the pre-discount price in this fixture
    expect(o.availability).toContain("noliktavā");
    expect(o.inStock).toBe(true);
    expect(o.url).toBe("https://partsale.lv/detail/W71252-mann-filter-ellas-filtrs");
  });

  it("extracts the product image, upsized from the 200px listing thumb", () => {
    expect(offers[0]!.imageUrl).toBe(
      "https://img.partsale.lv/images/800/aaea3bd6e7451f78a023cff3ee356f107a293c37.jpg",
    );
  });

  it("extracts spec attributes from the listing", () => {
    const attrs = offers[0]!.attributes;
    expect(attrs).toContainEqual({ label: "Filtra izpildījums", value: "Uzskrūvējams filtrs" });
    expect(attrs).toContainEqual({ label: "Augstums [mm]", value: "92" });
    expect(attrs.length).toBeGreaterThanOrEqual(8);
  });
});
