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

// Called from CartContent.tsx when a shopper clicks "Anwenden" — read-only
// check (active/window/minOrderValue/remaining-redemptions), does NOT
// increment the redemption counter. That only happens in /redeem, at
// actual purchase time (see CheckoutContent.tsx's handlePurchase()).
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({ valid: false, reason: "Bitte einen Code eingeben." }, { status: 400 });
  }

  const result = await validateDiscountCode(code, subtotal);
  if (!result.valid) return NextResponse.json(result);

  return NextResponse.json({ valid: true, type: result.doc.type, value: result.doc.value });
}
