import catalog from "@/data/products.json";
import type { CatalogProvider, Product, ProductFilters } from "@/lib/headless/types";

const products = catalog satisfies Product[];

function normalize(value: string): string {
  return value.toLocaleLowerCase("es").normalize("NFD").replace(/[\u0300-\u036f]/g, "");
}

function matches(product: Product, filters: ProductFilters): boolean {
  if (filters.category && filters.category !== "Todos" && product.category !== filters.category) return false;
  if (filters.collection && product.collection !== filters.collection) return false;
  if (filters.brand && product.brand !== filters.brand) return false;
  if (filters.ageRange && product.ageRange !== filters.ageRange) return false;
  if (filters.minPrice !== undefined && product.price !== null && product.price < filters.minPrice) return false;
  if (filters.maxPrice !== undefined && product.price !== null && product.price > filters.maxPrice) return false;
  if (filters.query) {
    const query = normalize(filters.query);
    const haystack = normalize([
      product.name,
      product.description,
      product.category,
      product.collection,
      product.brand,
      ...product.tags,
    ].join(" "));
    if (!haystack.includes(query)) return false;
  }
  return true;
}

export const mockCatalogProvider: CatalogProvider = {
  async getProducts(filters = {}) {
    return products.filter((product) => matches(product, filters));
  },
  async getProductBySlug(slug) {
    return products.find((product) => product.slug === slug) ?? null;
  },
  async searchProducts(query, limit = 6) {
    return products.filter((product) => matches(product, { query })).slice(0, limit);
  },
};
