// Server-only — imported exclusively by app/api/stock-notifications/route.ts.
// Reuses ORDER_SERVICE_SECRET rather than a new dedicated secret, matching
// StockNotifications.ts's own choice on the backend (see that collection's
// comment) — it's already the general-purpose "frontend server calling
// into Payload" credential used by getWishlistEnabled/getSearchEnabled/etc.
const PAYLOAD_URL = process.env.PAYLOAD_URL || "https://payload.mk360.de";
const SERVICE_SECRET = process.env.ORDER_SERVICE_SECRET || "";

export async function createStockNotification(email: string, productId: number, variantName: string): Promise<{ ok: boolean; reason?: string }> {
  const res = await fetch(`${PAYLOAD_URL}/api/stock-notifications`, {
    method: "POST",
    headers: { "Content-Type": "application/json", "x-order-service-secret": SERVICE_SECRET },
    body: JSON.stringify({ email, product: productId, variantName }),
  });
  if (res.ok) return { ok: true };

  // The (tenant, email, product, variantName) unique index rejects a
  // second signup for the same thing with a 400 — read as "already on the
  // list", not a real error, so the UI can still show success rather than
  // a confusing failure for someone who's already signed up.
  if (res.status === 400) return { ok: true };

  console.error(`createStockNotification: Payload returned ${res.status} ${res.statusText}`);
  return { ok: false, reason: "Eintragen hat nicht geklappt. Bitte versuch es später erneut." };
}
