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","city","consent"])if(!x[f])return jsonError(`Please provide ${f}.`);if(!/^\S+@\S+\.\S+$/.test(x.email))return jsonError("Enter a valid email address.");const event=await db().prepare("SELECT * FROM events WHERE registration_open=1 ORDER BY created_at DESC LIMIT 1").first<Record<string,unknown>>();if(!event)return jsonError("Registration is not currently available.",503);const count=Math.min(10,Math.max(1,Number(x.attendeeCount)||1));const seq=await db().prepare("SELECT COUNT(*) AS total FROM registrations WHERE event_id=?").bind(event.id).first<{total:number}>();const ref=`${event.registration_prefix}-${String(Number(seq?.total||0)+1).padStart(6,"0")}`;const id=uid("reg_");const due=Number(event.registration_fee||0)*count;await db().prepare("INSERT INTO registrations(id,event_id,registration_number,first_name,last_name,email,phone,country,city,state,age_range,church,role,source,attendance_type,attendee_count,notes,consent,communication_consent,status,payment_status,amount_due) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)").bind(id,event.id,ref,x.firstName.trim(),x.lastName.trim(),x.email.toLowerCase(),x.phone.trim(),x.country,x.city,x.state||null,x.ageRange||null,x.church||null,x.role||null,x.source||null,x.attendanceType||"in-person",count,x.notes||null,1,x.communicationConsent?1:0,due>0?"pending":"confirmed",due>0?"pending":"unpaid",due).run();await db().prepare("INSERT INTO activity_logs(id,registration_id,action,detail) VALUES(?,?,?,?)").bind(uid("act_"),id,"registration_submitted","Registration received").run();if(due>0){const payId=uid("pay_");await db().prepare("INSERT INTO payments(id,event_id,registration_id,purpose,amount,currency,status) VALUES(?,?,?,?,?,?,?)").bind(payId,event.id,id,"registration",due,event.currency,"pending").run();const checkout=await createStripeCheckout({paymentId:payId,amount:due,currency:String(event.currency),email:x.email,name:`${x.firstName} ${x.lastName}`,purpose:"registration",registrationId:id});if(!checkout)return jsonError("Registration saved, but online payment is not configured. Contact the conference office with reference "+ref,503);await db().prepare("UPDATE payments SET checkout_session_id=? WHERE id=?").bind(checkout.id,payId).run();return Response.json({url:checkout.url,reference:ref})}return Response.json({reference:ref},{status:201})}catch(e){console.error(e);return jsonError("Registration could not be completed. Please try again.",500)}}
