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

export async function POST(req: Request) {
  const limited = rateLimit(`quote:${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 = quoteRequestSchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json({ error: 'invalid_payload', issues: parsed.error.issues }, { status: 400 });
  }

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

  const quote = await prisma.quoteRequest.create({
    data: {
      fullName,
      email,
      phone,
      city: city ?? undefined,
      message: message ?? undefined,
      locale,
      items
    }
  });

  const itemsList = items.map((i) => `- ${i.name ?? i.sku} × ${i.quantity}`).join('\n');

  // Notification only — never blocks the response if SMTP is not configured.
  await sendAdminNotification({
    subject: `Nouvelle demande de devis — ${fullName}`,
    text: [
      `Nom: ${fullName}`,
      `Email: ${email}`,
      `Téléphone: ${phone}`,
      city ? `Ville: ${city}` : null,
      message ? `Message: ${message}` : null,
      '',
      'Articles demandés:',
      itemsList || '(aucun)'
    ]
      .filter(Boolean)
      .join('\n')
  });

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