export const dynamic = 'force-dynamic';
import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';

export async function POST(request: Request) {
  try {
    const data = await request.json();
    if (!data?.name || !data?.email || !data?.message) {
      return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
    }

    const lead = await prisma.lead.create({
      data: {
        name: data.name,
        email: data.email,
        phone: data?.phone ?? null,
        message: data.message,
        source: data?.source ?? 'CONTACT_FORM',
        vehicleId: data?.vehicleId ?? null,
      },
    });

    // Send email notification
    try {
      const appUrl = process.env.NEXTAUTH_URL ?? '';
      const appName = 'Evo Truck Sales';
      const htmlBody = `
        <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
          <div style="background: #DC2626; padding: 20px; border-radius: 8px 8px 0 0;">
            <h2 style="color: white; margin: 0;">Nueva Consulta Recibida</h2>
          </div>
          <div style="background: #f9fafb; padding: 20px; border-radius: 0 0 8px 8px;">
            <p style="margin: 10px 0;"><strong>Nombre:</strong> ${data?.name ?? ''}</p>
            <p style="margin: 10px 0;"><strong>Email:</strong> <a href="mailto:${data?.email ?? ''}">${data?.email ?? ''}</a></p>
            ${data?.phone ? `<p style="margin: 10px 0;"><strong>Teléfono:</strong> ${data.phone}</p>` : ''}
            <p style="margin: 10px 0;"><strong>Fuente:</strong> ${data?.source ?? 'Formulario de Contacto'}</p>
            <div style="background: white; padding: 15px; border-radius: 4px; border-left: 4px solid #DC2626; margin: 15px 0;">
              <strong>Mensaje:</strong><br/>${data?.message ?? ''}
            </div>
            <p style="color: #666; font-size: 12px;">Enviado: ${new Date().toLocaleString('es-US')}</p>
          </div>
        </div>
      `;

      await fetch('https://apps.abacus.ai/api/sendNotificationEmail', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          deployment_token: process.env.ABACUSAI_API_KEY,
          app_id: process.env.WEB_APP_ID,
          notification_id: process.env.NOTIF_ID_CONTACT_FORM_SUBMISSION,
          subject: `Nueva consulta de ${data?.name ?? 'Cliente'}`,
          body: htmlBody,
          is_html: true,
          recipient_email: 'junior@evotrucksales.com',
          reply_to: data?.email,
          sender_email: appUrl ? `noreply@${new URL(appUrl).hostname}` : 'noreply@evotrucksales.com',
          sender_alias: appName,
        }),
      });
    } catch (emailError: any) {
      console.error('Email notification error:', emailError);
    }

    return NextResponse.json({ success: true, id: lead?.id });
  } catch (error: any) {
    console.error('Contact error:', error);
    return NextResponse.json({ error: 'Failed to submit' }, { status: 500 });
  }
}
