/**
 * Server Actions for form submissions
 * These run on the server and can safely use API_KEY without exposing it to the browser
 */

'use server';

const API_URL = process.env.API_URL || 'http://localhost:3000/api/v1';
const API_KEY = process.env.API_KEY || '';

interface ContactFormResult {
  success: boolean;
  message?: string;
  error?: string;
  /** Present on lead form success; use for Meta Pixel dedup: fbq('track', 'Lead', {}, { eventID: eventId }) */
  eventId?: string;
}

/**
 * Submit contact form via Server Action
 */
export async function submitContactFormAction(formData: FormData): Promise<ContactFormResult> {
  try {
    // Extract and validate form data
    const firstName = formData.get('firstName')?.toString().trim() || '';
    const lastName = formData.get('lastName')?.toString().trim() || '';
    const email = formData.get('email')?.toString().trim() || '';
    const phone = formData.get('phone')?.toString().trim() || '';
    const message = formData.get('message')?.toString().trim() || '';
    
    // Basic validation
    if (!firstName || !lastName || !email || !message) {
      return {
        success: false,
        error: 'Please fill in all required fields.',
      };
    }
    
    // Combine first and last name
    const name = `${firstName} ${lastName}`;
    
    const payload = {
      name,
      email,
      phone,
      message,
      source: 'contact_form'
    };
    
    // Make API call server-side
    const response = await fetch(`${API_URL}/public/form_submissions`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-API-Key': API_KEY,
      },
      body: JSON.stringify(payload),
    });
    
    const data = await response.json();
    
    if (!response.ok) {
      return {
        success: false,
        error: data.error || 'Failed to submit contact form. Please try again.',
      };
    }
    
    return {
      success: true,
      message: data.message || 'Thank you for contacting us! We\'ll get back to you soon.',
    };
  } catch (error) {
    console.error('Contact form submission error:', error);
    return {
      success: false,
      error: 'Network error. Please try again later.',
    };
  }
}

/**
 * Submit lead form via Server Action
 */
export async function submitLeadFormAction(formData: FormData): Promise<ContactFormResult> {
  try {
    // Extract and validate form data
    const firstName = formData.get('firstName')?.toString().trim() || '';
    const lastName = formData.get('lastName')?.toString().trim() || '';
    const email = formData.get('email')?.toString().trim() || '';
    const phone = formData.get('phone')?.toString().trim() || '';
    const message = formData.get('message')?.toString().trim() || '';
    
    // Basic validation
    if (!firstName || !lastName || !email || !message) {
      return {
        success: false,
        error: 'Please fill in all required fields.',
      };
    }
    
    const payload = {
      formType: 'lead',
      firstName,
      lastName,
      email,
      phone,
      message,
    };

    const response = await fetch(`${API_URL}/public/form_submissions`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-API-Key': API_KEY,
      },
      body: JSON.stringify(payload),
    });
    
    const data = await response.json();
    
    if (!response.ok) {
      return {
        success: false,
        error: data.error || 'Failed to submit lead form. Please try again.',
      };
    }

    const eventId = data.data?.event_id ?? undefined;

    return {
      success: true,
      message: data.message || 'Thank you! We\'ll be in touch soon.',
      ...(eventId && { eventId }),
    };
  } catch (error) {
    console.error('Lead form submission error:', error);
    return {
      success: false,
      error: 'Network error. Please try again later.',
    };
  }
}
