import { NextResponse } from "next/server";
import { validateDiscountCode, redeemDiscountCode } from "../../../lib/discountServer";

// Called once, from CheckoutContent.tsx's handlePurchase(), right before
// the OrderSnapshot is written — re-validates (the window/limit may have
// changed since the cart-side /validate check, however unlikely) and only
// then increments the redemption counter. If this fails, the caller must
// not complete the purchase with a dead code silently still showing as
// applied.
export async function POST(request: Request) {
  const body = await request.json().catch(() => null);
  const code = typeof body?.code === "string" ? body.code : "";
  const subtotal = typeof body?.subtotal === "number" ? body.subtotal : 0;

  if (!code) {
    return NextResponse.json({ redeemed: false, reason: "Kein Code angegeben." }, { status: 400 });
  }

  const result = await validateDiscountCode(code, subtotal);
  if (!result.valid) return NextResponse.json({ redeemed: false, reason: result.reason });

  const ok = await redeemDiscountCode(result.doc);
  if (!ok) return NextResponse.json({ redeemed: false, reason: "Rabattcode konnte nicht eingelöst werden." });

  return NextResponse.json({ redeemed: true });
}
