import { NextRequest, NextResponse } from 'next/server';
import { validateCoupon, getCoupons, saveCoupons } from '@/lib/db';

export async function POST(req: NextRequest) {
  try {
    const { code, amount } = await req.json();
    const result = validateCoupon(code, amount || 0);
    if (!result.valid || !result.coupon) {
      return NextResponse.json({ success: false, message: result.message }, { status: 400 });
    }
    // Increment usage
    const coupons = getCoupons();
    const idx = coupons.findIndex(c => c.code === code.toUpperCase());
    if (idx !== -1) { coupons[idx].usedCount++; saveCoupons(coupons); }

    return NextResponse.json({
      success: true,
      coupon: result.coupon.code,
      type: result.coupon.type,
      value: result.coupon.value,
      message: result.message,
    });
  } catch (e: any) {
    return NextResponse.json({ success: false, message: e.message }, { status: 500 });
  }
}
