import { createStripeCheckout,db,jsonError,uid } from "@/lib/server";
export async function POST(request:Request){try{const x=await request.json() as Record<string,string>;for(const f of ["firstName","lastName","email","phone","country","amount"])if(!x[f])return jsonError(`Please provide ${f}.`);const amount=Number(x.amount);if(!Number.isFinite(amount)||amount<1||amount>100000)return jsonError("Enter a contribution between $1 and $100,000.");const event=await db().prepare("SELECT * FROM events ORDER BY created_at DESC LIMIT 1").first<Record<string,unknown>>();if(!event)return jsonError("Conference support is not currently available.",503);const id=uid("pay_");await db().prepare("INSERT INTO payments(id,event_id,supporter_name,supporter_email,supporter_phone,supporter_country,supporter_message,purpose,amount,currency,status) VALUES(?,?,?,?,?,?,?,?,?,?,?)").bind(id,event.id,`${x.firstName} ${x.lastName}`,x.email.toLowerCase(),x.phone,x.country,x.message||null,"support",amount,event.currency,"pending").run();const checkout=await createStripeCheckout({paymentId:id,amount,currency:String(event.currency),email:x.email,name:`${x.firstName} ${x.lastName}`,purpose:"support"});if(!checkout)return jsonError("Support payment is saved but Stripe is not configured yet. Please contact the conference office.",503);await db().prepare("UPDATE payments SET checkout_session_id=? WHERE id=?").bind(checkout.id,id).run();return Response.json({url:checkout.url})}catch(e){console.error(e);return jsonError("Payment could not be started. Please try again.",500)}}
