// Server-only — shared by app/api/checkout/route.ts and
// app/api/account/cart/route.ts. Fetched directly (not via lib/payload.ts's
// getProducts()) because that helper's mapped Product type drops the
// numeric Payload id, which both callers need (Orders.items.product /
// Customers.cart.product relationships) alongside the raw, un-trusted-by-
// the-client price.
const PAYLOAD_URL = process.env.PAYLOAD_URL || "https://payload.mk360.de";
const TENANT_SLUG = "einfach-produktiv";

export type RawProductVariant = {
  name: string;
  sku: string | null;
  priceOverride: number | null;
  trackInventory: boolean;
  stock: number | null;
  allowBackorder: boolean;
};

export type RawProduct = {
  id: number;
  slug: string;
  name: string;
  sku: string | null;
  price: number;
  active: boolean;
  image: { url: string } | number | null;
  taxRatePercent: number | null;
  noShippingCost: boolean;
  bundleItems: { product: { id: number; name: string } | number; quantity: number }[] | null;
  variants: RawProductVariant[] | null;
  trackInventory: boolean;
  stock: number | null;
  allowBackorder: boolean;
};

export async function fetchProductsBySlug(): Promise<Map<string, RawProduct>> {
  // depth=2, not 1 — `image` only needs depth 1 (order-confirmation
  // email's product thumbnails, app/lib/orderEmail.ts), but resolving
  // `bundleItems.product.name` (needed to build a bundle's readable
  // contents snapshot at checkout, see app/api/checkout/route.ts) is a
  // relationship nested inside an array field, one level deeper.
  const params = new URLSearchParams({ "where[tenant.slug][equals]": TENANT_SLUG, depth: "2", limit: "100" });
  const res = await fetch(`${PAYLOAD_URL}/api/products?${params}`, { cache: "no-store" });
  const map = new Map<string, RawProduct>();
  if (!res.ok) return map;
  const data: { docs?: RawProduct[] } = await res.json();
  for (const doc of data.docs ?? []) map.set(doc.slug, doc);
  return map;
}
