import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { contactMessageSchema } from '@/lib/validation';
import { rateLimit, getClientKey } from '@/lib/rate-limit';
import { sendAdminNotification } from '@/lib/mailer';

export async function POST(req: Request) {
  const limited = rateLimit(`contact:${getClientKey(req)}`, 5, 60_000);
  if (!limited.ok) {
    return NextResponse.json({ error: 'rate_limited' }, { status: 429 });
  }

  const body = await req.json().catch(() => null);
  const parsed = contactMessageSchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json({ error: 'invalid_payload', issues: parsed.error.issues }, { status: 400 });
  }

  const { fullName, email, phone, subject, message, locale } = parsed.data;

  const entry = await prisma.contactMessage.create({
    data: {
      fullName,
      email,
      phone: phone ?? undefined,
      subject: subject ?? undefined,
      message,
      locale
    }
  });

  // Notification only — never blocks the response if SMTP is not configured.
  await sendAdminNotification({
    subject: `Nouveau message de contact — ${subject ?? 'sans objet'}`,
    text: [
      `Nom: ${fullName}`,
      `Email: ${email}`,
      `Téléphone: ${phone ?? '-'}`,
      `Objet: ${subject ?? '-'}`,
      `Locale: ${locale}`,
      '',
      message
    ].join('\n')
  });

  return NextResponse.json({ id: entry.id }, { status: 201 });
}
