import { getProducts } from "@/lib/products";

/**
 * GET /api/products — the minimal catalogue snapshot.
 *
 * The cart needs current stock and price to reconcile the lines it stored in
 * `localStorage`, and it runs in the browser. Reading `data/products.json`
 * there is impossible, so the server exposes just those fields instead of
 * letting a client component import a module that uses `node:fs`.
 */
export async function GET(): Promise<Response> {
  try {
    const products = await getProducts();

    return Response.json(
      {
        count: products.length,
        products: products.map((product) => ({
          id: product.id,
          name: product.name,
          price: product.price,
          image: product.image,
          brand: product.brand,
          stock: product.stock,
        })),
      },
      { headers: { "cache-control": "no-store" } },
    );
  } catch (error) {
    console.error("[api/products] failed:", error);
    return Response.json(
      { error: { code: "CATALOGUE_UNAVAILABLE", message: "The catalogue could not be read." } },
      { status: 500 },
    );
  }
}