'use server';

/**
 * Server Actions for form submissions.
 * Runs on the server — API_KEY is never exposed to the browser.
 */

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;
}

function extractFormFields(formData: FormData) {
  return {
    firstName: formData.get('firstName')?.toString().trim() || '',
    lastName: formData.get('lastName')?.toString().trim() || '',
    email: formData.get('email')?.toString().trim() || '',
    phone: formData.get('phone')?.toString().trim() || '',
    message: formData.get('message')?.toString().trim() || '',
  };
}

async function postFormSubmission(payload: Record<string, unknown>): Promise<Response> {
  return fetch(`${API_URL}/public/form_submissions`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-Key': API_KEY,
    },
    body: JSON.stringify(payload),
  });
}

export async function submitContactFormAction(formData: FormData): Promise<ContactFormResult> {
  const { firstName, lastName, email, phone, message } = extractFormFields(formData);

  if (!firstName || !lastName || !email || !message) {
    return { success: false, error: 'Please fill in all required fields.' };
  }

  try {
    const res = await postFormSubmission({
      name: `${firstName} ${lastName}`,
      email,
      phone,
      message,
      source: 'contact_form',
    });
    const data = await res.json();
    if (!res.ok) return { success: false, error: data.error || 'Failed to submit. Please try again.' };
    return { success: true, message: data.message || "Thank you for contacting us! We'll get back to you soon." };
  } catch {
    return { success: false, error: 'Network error. Please try again later.' };
  }
}

export async function submitLeadFormAction(formData: FormData): Promise<ContactFormResult> {
  const { firstName, lastName, email, phone, message } = extractFormFields(formData);

  if (!firstName || !lastName || !email || !message) {
    return { success: false, error: 'Please fill in all required fields.' };
  }

  try {
    const res = await postFormSubmission({ formType: 'lead', firstName, lastName, email, phone, message });
    const data = await res.json();
    if (!res.ok) return { success: false, error: data.error || 'Failed to submit. Please try again.' };
    const eventId: string | undefined = data.data?.event_id ?? undefined;
    return { success: true, message: data.message || "Thank you! We'll be in touch soon.", ...(eventId && { eventId }) };
  } catch {
    return { success: false, error: 'Network error. Please try again later.' };
  }
}
