import { NextRequest, NextResponse } from "next/server"; import { createClient } from "next-sanity"; import { Resend } from "resend"; import { apiVersion, dataset, projectId } from "@/sanity/lib/env"; export async function POST(req: NextRequest) { try { const body = await req.json(); const { coupleNames, email, whatsapp, weddingDate, destinationRegion, guestCount, budgetRange, serviceTrack, message, } = body; // Basic validation if (!coupleNames || !email) { return NextResponse.json( { error: "Couple names and email are required." }, { status: 400 } ); } const submittedAt = new Date().toISOString(); let savedToSanity = false; let emailDispatched = false; // 1. PERSIST TO SANITY CMS (Free NoSQL Cloud Database) const writeToken = process.env.SANITY_API_WRITE_TOKEN || process.env.SANITY_API_TOKEN; if (writeToken && projectId) { try { const writeClient = createClient({ projectId, dataset, apiVersion, useCdn: false, token: writeToken, }); await writeClient.create({ _type: "inquiry", status: "new", coupleNames, email, whatsapp: whatsapp || "", weddingDate: weddingDate || "", destinationRegion: destinationRegion || "", guestCount: guestCount || "", budgetRange: budgetRange || "", serviceTrack: serviceTrack || "", message: message || "", submittedAt, }); savedToSanity = true; } catch (sanityErr) { console.error("[Contact API] Failed to write to Sanity:", sanityErr); } } else { console.warn( "[Contact API] SANITY_API_WRITE_TOKEN not configured. Data received in dev:", { coupleNames, email, destinationRegion, budgetRange } ); } // 2. DISPATCH NOTIFICATION EMAIL VIA RESEND (Free 3,000 emails/month) const resendApiKey = process.env.RESEND_API_KEY; if (resendApiKey) { try { const resend = new Resend(resendApiKey); await resend.emails.send({ from: "Vietnam Wedding Guide ", to: [process.env.CONTACT_NOTIFICATION_EMAIL || "vietnamweddingguide@gmail.com"], replyTo: email, subject: `✨ New Wedding Inquiry from ${coupleNames} (${destinationRegion || "Vietnam"})`, html: `

New Advisory Inquiry Received

Submitted at ${new Date(submittedAt).toLocaleString()}

Couple's Names:${coupleNames}
Email:${email}
WhatsApp:${whatsapp || "Not provided"}
Wedding Date:${weddingDate || "Flexible"}
Destination:${destinationRegion || "Unspecified"}
Guest Count:${guestCount || "Unspecified"}
Budget Range:${budgetRange || "Unspecified"}
Service Track:${serviceTrack || "General Consultation"}
${ message ? `

Client Message / Key Challenges:

${message}

` : "" }

View and manage this lead in Sanity Studio →

`, }); emailDispatched = true; } catch (resendErr) { console.error("[Contact API] Failed to send email via Resend:", resendErr); } } return NextResponse.json({ success: true, savedToSanity, emailDispatched, message: "Inquiry successfully received.", }); } catch (err: any) { console.error("[Contact API] Unhandled error:", err); return NextResponse.json( { error: "Internal server error occurred while processing inquiry." }, { status: 500 } ); } }