const META_PHONE_NUMBER_ID = process.env.WHATSAPP_PHONE_NUMBER_ID;
const META_ACCESS_TOKEN = process.env.WHATSAPP_ACCESS_TOKEN;
const META_BUSINESS_ACCOUNT_ID = process.env.WHATSAPP_BUSINESS_ACCOUNT_ID;

export async function sendWhatsAppMessage(
  phoneNumber: string,
  message: string
): Promise<{ success: boolean; error?: string }> {
  if (!META_PHONE_NUMBER_ID || !META_ACCESS_TOKEN) {
    console.warn('WhatsApp credentials not configured');
    return { success: false, error: 'WhatsApp not configured' };
  }

  try {
    // Format phone number: remove any non-digits and ensure it starts with country code
    const cleanPhone = phoneNumber.replace(/\D/g, '');
    const formattedPhone = cleanPhone.startsWith('44') ? cleanPhone : `44${cleanPhone.replace(/^0/, '')}`;

    const response = await fetch(
      `https://graph.instagram.com/v18.0/${META_PHONE_NUMBER_ID}/messages`,
      {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${META_ACCESS_TOKEN}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          messaging_product: 'whatsapp',
          recipient_type: 'individual',
          to: formattedPhone,
          type: 'text',
          text: {
            preview_url: false,
            body: message,
          },
        }),
      }
    );

    const data = (await response.json()) as { messages?: Array<{ id: string }>; error?: { message: string } };

    if (!response.ok) {
      const errorMsg = data.error?.message || 'Failed to send WhatsApp message';
      console.error('WhatsApp error:', errorMsg);
      return { success: false, error: errorMsg };
    }

    console.log('✓ WhatsApp message sent:', formattedPhone);
    return { success: true };
  } catch (error) {
    const errorMsg = error instanceof Error ? error.message : 'Unknown error';
    console.error('WhatsApp send error:', errorMsg);
    return { success: false, error: errorMsg };
  }
}

export function formatPhoneForDisplay(phone: string): string {
  const clean = phone.replace(/\D/g, '');
  if (clean.length === 10) return `+44 ${clean.slice(0, 4)} ${clean.slice(4, 8)} ${clean.slice(8)}`;
  if (clean.length === 12 && clean.startsWith('44')) return `+${clean.slice(0, 2)} ${clean.slice(2, 5)} ${clean.slice(5, 8)} ${clean.slice(8)}`;
  return phone;
}
