import type { APIRoute } from 'astro'; import { env } from 'cloudflare:workers'; import { sendEmail } from '@/lib/email'; import general from '@/content/settings/general.json'; export const prerender = false; interface ContactBody { fullName: string; email: string; phone: string; message: string; } function isValidBody(body: unknown): body is ContactBody { if (typeof body !== 'object' || body === null) return false; const b = body as Record; return ( typeof b.fullName === 'string' && b.fullName.trim().length > 0 && typeof b.email === 'string' && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(b.email) && typeof b.phone === 'string' && /^[+\d][\d\s\-().]{6,19}$/.test(b.phone.trim()) && typeof b.message === 'string' && b.message.trim().length > 0 ); } function buildContactNotificationHtml(data: ContactBody): string { return `

Nouveau message de contact

Cachet Peintres Décorateurs

Vous avez reçu un nouveau message de ${data.fullName}.

Nom ${data.fullName}
Courriel ${data.email}
Téléphone ${data.phone}

Message

${data.message}
Répondre à ${data.fullName}

Cachet Peintres Décorateurs · CACHETDECO · RBQ 5839 8736 01

`; } export const POST: APIRoute = async ({ request }) => { let body: unknown; try { body = await request.json(); } catch { return new Response(JSON.stringify({ success: false, error: 'Invalid request body.' }), { status: 400, headers: { 'Content-Type': 'application/json' }, }); } if (!isValidBody(body)) { return new Response(JSON.stringify({ success: false, error: 'Missing or invalid fields.' }), { status: 422, headers: { 'Content-Type': 'application/json' }, }); } const apiKey = (env as unknown as Record).RESEND_API_KEY; const toAddress = general.emailToContact?.trim(); const fromAddress = general.emailFromContact?.trim(); if (!apiKey || !toAddress || !fromAddress) { return new Response(JSON.stringify({ success: false, error: 'Server configuration missing.', apiKey, toAddress, fromAddress }), { status: 500, headers: { 'Content-Type': 'application/json' }, }); } try { await sendEmail(apiKey, { from: fromAddress, to: toAddress, replyTo: body.email, subject: `Nouveau message — ${body.fullName}`, html: buildContactNotificationHtml(body), }); } catch (e) { console.error(e); return new Response(JSON.stringify({ success: false, error: 'Failed to send email.' }), { status: 502, headers: { 'Content-Type': 'application/json' }, }); } return new Response(JSON.stringify({ success: true }), { status: 200, headers: { 'Content-Type': 'application/json' }, }); };