import { NextResponse } from "next/server";
import { isValidEmail } from "../../lib/email";
import { createStockNotification } from "../../lib/stockNotifications";

export async function POST(request: Request) {
  const body = await request.json().catch(() => null);
  const email = typeof body?.email === "string" ? body.email.trim() : "";
  const productId = Number(body?.productId);
  const variantName = typeof body?.variantName === "string" ? body.variantName : "";

  if (!isValidEmail(email)) {
    return NextResponse.json({ ok: false, reason: "Bitte gib eine gültige E-Mail-Adresse ein." }, { status: 400 });
  }
  if (!Number.isInteger(productId) || productId <= 0) {
    return NextResponse.json({ ok: false, reason: "Ungültiges Produkt." }, { status: 400 });
  }

  const result = await createStockNotification(email, productId, variantName);
  if (!result.ok) return NextResponse.json(result, { status: 500 });
  return NextResponse.json({ ok: true });
}
