import { NextRequest, NextResponse } from 'next/server';

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

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

    // Get NocoDB configuration
    const NOCODB_API_TOKEN = process.env.NOCODB_API_TOKEN;
    const NOCODB_BASE_URL = process.env.NOCODB_BASE_URL || 'https://app.nocodb.com';
    const NOCODB_TABLE_ID = process.env.NOCODB_TABLE_ID || 'contacts';

    if (!NOCODB_API_TOKEN) {
      console.error('NOCODB_API_TOKEN not configured');
      return NextResponse.json(
        { error: 'Server configuration error' },
        { status: 500 }
      );
    }

    // Prepare data for NocoDB with correct field names
    // Ensure phone number has '+' prefix if it doesn't already
    const phoneNumber = body.phone ?
      (body.phone.startsWith('+') ? body.phone : `+${body.phone}`) : '';

    const contactData = {
      fields: {
        'First Name': body.firstName,
        'Last Name': body.lastName,
        'Full Name': `${body.firstName} ${body.lastName}`,
        'Email': body.email,
        'Telephone': phoneNumber,
        'Message': body.message || '',
      }
    };

    // Send to NocoDB - using v3 API with correct project ID
    const nocdbResponse = await fetch(
      `${NOCODB_BASE_URL}/api/v3/data/p4bq8r1rmsfu77o/${NOCODB_TABLE_ID}/records`,
      {
        method: 'POST',
        headers: {
          'accept': 'application/json',
          'Content-Type': 'application/json',
          'xc-token': NOCODB_API_TOKEN,
        },
        body: JSON.stringify(contactData),
      }
    );

    if (!nocdbResponse.ok) {
      const errorText = await nocdbResponse.text();
      console.error('NocoDB error:', errorText);
      throw new Error('Failed to save contact');
    }

    const result = await nocdbResponse.json();

    // Send success response
    return NextResponse.json(
      {
        success: true,
        message: 'Contact form submitted successfully',
        id: result.Id || result.id,
      },
      { status: 200 }
    );
  } catch (error) {
    console.error('Contact form error:', error);
    return NextResponse.json(
      { error: 'Failed to process contact form' },
      { status: 500 }
    );
  }
}