import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { trodo } from "../src/adapters/trodo.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 json = readFileSync("fixtures/trodo/0986452041.json", "utf-8");

describe("trodo adapter (fixture: 0986452041, recorded 2026-07-12 via solved session)", () => {
  const offers = trodo.parse(json, normalizeQuery("0986452041")!);

  it("maps page-1 products to priced offers", () => {
    expect(offers.length).toBeGreaterThan(0);
    for (const o of offers) expect(o.priceEur).toBeGreaterThan(0);
  });

  it("every offer passes schema validation", () => {
    for (const o of offers) expect(OfferSchema.safeParse(o).success, JSON.stringify(o)).toBe(true);
  });

  it("surfaces the searched BOSCH part as an exact-number match", () => {
    const bosch = offers.find((o) => canonicalize(o.partNumber) === "0986452041");
    expect(bosch).toBeDefined();
    expect(bosch!.brand).toBe("BOSCH");
    expect(bosch!.partNumber).toBe("0 986 452 041");
    expect(bosch!.priceEur).toBe(6.32);
    expect(bosch!.availability).toBe("Pieejams");
    expect(bosch!.url).toBe("https://www.trodo.lv/ellas-filtrs-bosch-0-986-452-041");
    expect(bosch!.imageUrl).toContain("picdn.trodo.com");
    expect(bosch!.attributes.length).toBeGreaterThan(0);
  });

  it("includes cross-brand analogues with their own part numbers", () => {
    const brands = new Set(offers.map((o) => o.brand));
    expect(brands.size).toBeGreaterThan(1); // not just BOSCH
    // distinct part numbers across analogues
    const parts = new Set(offers.map((o) => canonicalize(o.partNumber)));
    expect(parts.size).toBeGreaterThan(1);
  });

  it("accepts a structurally valid no-result envelope", () => {
    expect(trodo.parse('[{"products":[]}]', normalizeQuery("NORESULT")!)).toEqual([]);
  });

  it.each(["[]", "{}", "not json"])(
    "rejects a transitional or malformed payload instead of reporting zero results: %s",
    (body) => {
      expect(() => trodo.parse(body, normalizeQuery("0986452041")!)).toThrow();
    },
  );
});
