/**
 * WORLDWIDE PHONE NUMBER FORMATTER
 * Supports 200+ countries with automatic country code detection
 * Production-ready with comprehensive validation
 */

const libphonenumber = require('libphonenumber-js');

/**
 * Format phone number for WhatsApp (worldwide support)
 * @param {string} phone - Phone number in any format
 * @param {string} defaultCountry - Default country code (ISO 2-letter, e.g., 'US', 'NG', 'BR')
 * @returns {string} - Formatted phone number for WhatsApp
 */
function pf(phone, defaultCountry = 'US') {
  if (!phone || typeof phone !== 'string') return '';
  
  // Remove all non-digit characters
  let phoneWa = phone.replace(/\D/g, '');
  
  if (phoneWa === '') return '';
  
  // Try to parse with libphonenumber for automatic detection
  try {
    const parsed = libphonenumber.parsePhoneNumber(phone, defaultCountry);
    if (parsed && parsed.isValid()) {
      // Return in E.164 format without the + sign (WhatsApp format)
      return parsed.number.replace('+', '');
    }
  } catch (error) {
    // If parsing fails, continue with manual formatting below
    console.log('Libphonenumber parsing failed, using manual formatting');
  }
  
  // Manual formatting rules for common cases
  
  /* Indonesia formatting */
  if (phoneWa.startsWith('08') && phoneWa.length >= 10 && phoneWa.length <= 13) {
    phoneWa = phoneWa.replace(/^08/, '628');
  } else if (phoneWa.startsWith('6208')) {
    phoneWa = phoneWa.replace(/^6208/, '628');
  }
  
  /* Italy formatting */
  else if (phoneWa.startsWith('3') && (phoneWa.length === 9 || phoneWa.length === 10)) {
    phoneWa = '39' + phoneWa;
  }
  
  /* Nigeria formatting */
  else if (phoneWa.startsWith('2340')) {
    phoneWa = phoneWa.replace(/^2340/, '234');
  } else if (phoneWa.startsWith('0') && phoneWa.length === 11) {
    // Nigerian local format 0803... -> 234803...
    phoneWa = '234' + phoneWa.substring(1);
  }
  
  /* Mexico formatting */
  else if (phoneWa.startsWith('52') && phoneWa.length === 12 && !phoneWa.startsWith('521')) {
    phoneWa = phoneWa.replace(/^52/, '521');
  }
  
  /* Argentina formatting */
  else if (phoneWa.startsWith('54') && phoneWa.length === 12 && !phoneWa.startsWith('549')) {
    phoneWa = phoneWa.replace(/^54/, '549');
  }
  
  /* Brazil formatting */
  else if (phoneWa.startsWith('55') && phoneWa.length === 13) {
    const isCellularPost = phoneWa.substr(-9).startsWith('9');
    if (!isCellularPost) {
      const ddd = parseInt(phoneWa.substr(2, 2));
      if (ddd > 30) {
        phoneWa = '55' + ddd + phoneWa.substr(-8);
      }
    }
  }
  
  /* United States/Canada formatting */
  else if (phoneWa.length === 10 && /^[2-9]\d{2}[2-9]\d{6}$/.test(phoneWa)) {
    // US/Canada local format -> add country code 1
    phoneWa = '1' + phoneWa;
  }
  
  /* UK formatting */
  else if (phoneWa.startsWith('0') && phoneWa.length === 11 && phoneWa.startsWith('07')) {
    // UK mobile 07... -> 447...
    phoneWa = '44' + phoneWa.substring(1);
  }
  
  /* India formatting */
  else if (phoneWa.startsWith('0') && phoneWa.length === 11 && phoneWa.startsWith('09')) {
    // India mobile 09... -> 919...
    phoneWa = '91' + phoneWa.substring(1);
  } else if (phoneWa.startsWith('91') && phoneWa.startsWith('910') && phoneWa.length === 13) {
    // Fix double 0: 9109... -> 919...
    phoneWa = '91' + phoneWa.substring(3);
  }
  
  /* South Africa formatting */
  else if (phoneWa.startsWith('0') && phoneWa.length === 10 && phoneWa.startsWith('0')) {
    // Could be South Africa 08... -> 278...
    phoneWa = '27' + phoneWa.substring(1);
  }
  
  /* Kenya formatting */
  else if (phoneWa.startsWith('0') && phoneWa.length === 10 && phoneWa.startsWith('07')) {
    // Kenya mobile 07... -> 2547...
    phoneWa = '254' + phoneWa.substring(1);
  }
  
  /* Ghana formatting */
  else if (phoneWa.startsWith('0') && phoneWa.length === 10 && phoneWa.startsWith('02')) {
    // Ghana mobile 02... -> 2332...
    phoneWa = '233' + phoneWa.substring(1);
  }
  
  /* Egypt formatting */
  else if (phoneWa.startsWith('0') && phoneWa.length === 11 && phoneWa.startsWith('01')) {
    // Egypt mobile 01... -> 201...
    phoneWa = '20' + phoneWa.substring(1);
  }
  
  /* Saudi Arabia formatting */
  else if (phoneWa.startsWith('0') && phoneWa.length === 10 && phoneWa.startsWith('05')) {
    // Saudi mobile 05... -> 9665...
    phoneWa = '966' + phoneWa.substring(1);
  }
  
  /* UAE formatting */
  else if (phoneWa.startsWith('0') && phoneWa.length === 10 && phoneWa.startsWith('05')) {
    // UAE mobile 05... -> 9715...
    phoneWa = '971' + phoneWa.substring(1);
  }
  
  /* Pakistan formatting */
  else if (phoneWa.startsWith('0') && phoneWa.length === 11 && phoneWa.startsWith('03')) {
    // Pakistan mobile 03... -> 923...
    phoneWa = '92' + phoneWa.substring(1);
  }
  
  /* Bangladesh formatting */
  else if (phoneWa.startsWith('0') && phoneWa.length === 11 && phoneWa.startsWith('01')) {
    // Bangladesh mobile 01... -> 8801...
    phoneWa = '880' + phoneWa.substring(1);
  }
  
  /* Philippines formatting */
  else if (phoneWa.startsWith('0') && phoneWa.length === 11 && phoneWa.startsWith('09')) {
    // Philippines mobile 09... -> 639...
    phoneWa = '63' + phoneWa.substring(1);
  }
  
  /* Malaysia formatting */
  else if (phoneWa.startsWith('0') && phoneWa.length === 10 && phoneWa.startsWith('01')) {
    // Malaysia mobile 01... -> 601...
    phoneWa = '60' + phoneWa.substring(1);
  }
  
  /* Singapore formatting */
  else if (phoneWa.startsWith('0') && phoneWa.length === 8 && phoneWa.startsWith('8')) {
    // Singapore mobile 8... -> 658...
    phoneWa = '65' + phoneWa.substring(1);
  } else if (phoneWa.length === 8 && phoneWa.startsWith('8')) {
    // Singapore mobile without 0: 8... -> 658...
    phoneWa = '65' + phoneWa;
  }
  
  /* Thailand formatting */
  else if (phoneWa.startsWith('0') && phoneWa.length === 10 && phoneWa.startsWith('08')) {
    // Thailand mobile 08... -> 668...
    phoneWa = '66' + phoneWa.substring(1);
  }
  
  /* Vietnam formatting */
  else if (phoneWa.startsWith('0') && phoneWa.length === 10 && phoneWa.startsWith('09')) {
    // Vietnam mobile 09... -> 849...
    phoneWa = '84' + phoneWa.substring(1);
  }
  
  /* Turkey formatting */
  else if (phoneWa.startsWith('0') && phoneWa.length === 11 && phoneWa.startsWith('05')) {
    // Turkey mobile 05... -> 905...
    phoneWa = '90' + phoneWa.substring(1);
  }
  
  /* Germany formatting */
  else if (phoneWa.startsWith('0') && phoneWa.length >= 10 && phoneWa.length <= 11 && phoneWa.startsWith('01')) {
    // Germany mobile 01... -> 491...
    phoneWa = '49' + phoneWa.substring(1);
  }
  
  /* France formatting */
  else if (phoneWa.startsWith('0') && phoneWa.length === 10 && phoneWa.startsWith('06')) {
    // France mobile 06... -> 336...
    phoneWa = '33' + phoneWa.substring(1);
  }
  
  /* Spain formatting */
  else if (phoneWa.startsWith('0') && phoneWa.length === 10 && phoneWa.startsWith('06')) {
    // Spain mobile 06... -> 346...
    phoneWa = '34' + phoneWa.substring(1);
  } else if (phoneWa.length === 9 && phoneWa.startsWith('6')) {
    // Spain mobile without 0: 6... -> 346...
    phoneWa = '34' + phoneWa;
  }
  
  /* Russia formatting */
  else if (phoneWa.startsWith('8') && phoneWa.length === 11) {
    // Russia mobile 8... -> 7...
    phoneWa = '7' + phoneWa.substring(1);
  }
  
  /* Australia formatting */
  else if (phoneWa.startsWith('0') && phoneWa.length === 10 && phoneWa.startsWith('04')) {
    // Australia mobile 04... -> 614...
    phoneWa = '61' + phoneWa.substring(1);
  }
  
  return phoneWa;
}

/**
 * Format to WhatsApp server format (s.whatsapp.net)
 * @param {string} phone - Phone number
 * @param {string} defaultCountry - Default country code
 * @returns {string} - phone@s.whatsapp.net
 */
function s_wa(phone, defaultCountry = 'US') {
  return `${pf(phone, defaultCountry)}@s.whatsapp.net`;
}

/**
 * Format to WhatsApp group format (g.us)
 * @param {string} phone - Group ID
 * @param {string} defaultCountry - Default country code
 * @returns {string} - groupid@g.us
 */
function g_us(phone, defaultCountry = 'US') {
  return `${pf(phone, defaultCountry)}@g.us`;
}

/**
 * Format to WhatsApp contact format (c.us)
 * @param {string} phone - Phone number
 * @param {string} defaultCountry - Default country code
 * @returns {string} - phone@c.us
 */
function c_us(phone, defaultCountry = 'US') {
  return `${pf(phone, defaultCountry)}@c.us`;
}

/**
 * Validate phone number
 * @param {string} phone - Phone number to validate
 * @param {string} defaultCountry - Default country code
 * @returns {boolean} - true if valid
 */
function isValidPhone(phone, defaultCountry = 'US') {
  if (!phone || typeof phone !== 'string') return false;
  
  try {
    const parsed = libphonenumber.parsePhoneNumber(phone, defaultCountry);
    return parsed && parsed.isValid();
  } catch (error) {
    // Fallback: check if formatted number is reasonable
    const formatted = pf(phone, defaultCountry);
    return formatted.length >= 7 && formatted.length <= 15 && /^\d+$/.test(formatted);
  }
}

/**
 * Get country code from phone number
 * @param {string} phone - Phone number
 * @param {string} defaultCountry - Default country code
 * @returns {string|null} - Country code (e.g., 'US', 'NG', 'BR') or null
 */
function getCountryCode(phone, defaultCountry = 'US') {
  try {
    const parsed = libphonenumber.parsePhoneNumber(phone, defaultCountry);
    return parsed && parsed.country ? parsed.country : null;
  } catch (error) {
    return null;
  }
}

/**
 * Format phone number to international format (E.164)
 * @param {string} phone - Phone number
 * @param {string} defaultCountry - Default country code
 * @returns {string} - Phone number in E.164 format (+1234567890)
 */
function toE164(phone, defaultCountry = 'US') {
  try {
    const parsed = libphonenumber.parsePhoneNumber(phone, defaultCountry);
    return parsed && parsed.isValid() ? parsed.number : '';
  } catch (error) {
    return '';
  }
}

module.exports = { 
  pf, 
  s_wa, 
  g_us, 
  c_us, 
  isValidPhone, 
  getCountryCode, 
  toE164 
};
