import { NextResponse } from 'next/server';

export async function POST(request: Request) {
  try {
    const data = await request.json();

    // Validate required fields
    const { firstName, lastName, email, phone, message } = data;

    if (!firstName || !lastName || !email || !phone) {
      return NextResponse.json(
        { error: 'Missing required fields' },
        { status: 400 }
      );
    }

    // Email validation regex
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      return NextResponse.json(
        { error: 'Invalid email address' },
        { status: 400 }
      );
    }

    // Log the submission (in production, you would:
    // 1. Send an email notification using SendGrid, Postmark, or Resend
    // 2. Store in a database like Supabase or PostgreSQL
    // 3. Integrate with CRM like HubSpot or Salesforce)

    console.log('Contact form submission received:', {
      firstName,
      lastName,
      email,
      phone,
      message: message || '(No message provided)',
      timestamp: new Date().toISOString()
    });

    // Simulate email sending (in production, replace with actual email service)
    // Example with Resend:
    // await resend.emails.send({
    //   from: 'onboarding@portamador.com',
    //   to: 'am@portamador.com',
    //   subject: `New Contact Form Submission from ${firstName} ${lastName}`,
    //   html: `
    //     <h2>New Contact Form Submission</h2>
    //     <p><strong>Name:</strong> ${firstName} ${lastName}</p>
    //     <p><strong>Email:</strong> ${email}</p>
    //     <p><strong>Phone:</strong> ${phone}</p>
    //     <p><strong>Message:</strong> ${message || 'No message provided'}</p>
    //   `
    // });

    // Return success response
    return NextResponse.json(
      {
        success: true,
        message: 'Thank you for your submission. We will contact you soon.',
        data: {
          firstName,
          lastName,
          email
        }
      },
      { status: 200 }
    );

  } catch (error) {
    console.error('Error processing contact form:', error);
    return NextResponse.json(
      { error: 'Internal server error. Please try again later.' },
      { status: 500 }
    );
  }
}