import type { CatalogProvider, Product } from "@/lib/headless/types";

async function medusaFetch<T>(path: string): Promise<T> {
  const baseUrl = process.env.MEDUSA_BACKEND_URL;
  if (!baseUrl) throw new Error("Medusa no está configurado.");
  const response = await fetch(`${baseUrl.replace(/\/$/, "")}${path}`, {
    headers: process.env.MEDUSA_PUBLISHABLE_KEY
      ? { "x-publishable-api-key": process.env.MEDUSA_PUBLISHABLE_KEY }
      : undefined,
    next: { revalidate: 300 },
  });
  if (!response.ok) throw new Error(`Medusa respondió HTTP ${response.status}`);
  return (await response.json()) as T;
}

function notImplemented(): never {
  throw new Error("Completa el mapeo Medusa → Product en lib/headless/providers/medusa.ts.");
}

export const medusaCatalogProvider: CatalogProvider = {
  async getProducts() {
    await medusaFetch<unknown>("/store/products?limit=24");
    return notImplemented();
  },
  async getProductBySlug(): Promise<Product | null> {
    return notImplemented();
  },
  async searchProducts(): Promise<Product[]> {
    return notImplemented();
  },
};
