/**
 * Phone Number Normalization & Matching
 * 
 * The #1 cause of lost leads is phone number format mismatches.
 * This module ensures consistent phone handling across the entire system.
 * 
 * Formats we handle:
 * - +966501234567 (international with +)
 * - 966501234567 (international without +)
 * - 0501234567 (local Saudi)
 * - 501234567 (no prefix)
 * - 966 50 123 4567 (with spaces)
 * - +966-50-123-4567 (with dashes)
 * 
 * We normalize everything to digits-only, then extract the significant digits.
 */

/**
 * Strip all non-digit characters from a phone number.
 */
export function stripPhone(phone: string): string {
  return phone.replace(/[^\d]/g, "");
}

/**
 * Normalize a phone number to a consistent format for storage and comparison.
 * Returns the phone number with country code, no +, no spaces.
 * 
 * If we can detect it's Saudi (starts with 966 or 05), we normalize to 966XXXXXXXXX.
 * Otherwise, we just strip non-digits.
 */
export function normalizePhone(phone: string): string {
  let digits = stripPhone(phone);

  // Remove leading zeros for numbers that start with 00 (international dial prefix)
  if (digits.startsWith("00")) {
    digits = digits.slice(2);
  }

  // Saudi numbers: 05XXXXXXXX → 9665XXXXXXXX (10 digits starting with 05)
  if (digits.startsWith("05") && digits.length === 10) {
    digits = "966" + digits.slice(1);
  }

  // Egyptian numbers: 01XXXXXXXXX → 201XXXXXXXXX (11 digits starting with 01)
  if (digits.startsWith("01") && digits.length === 11) {
    digits = "20" + digits.slice(1);
  }

  return digits;
}

/**
 * Get the significant suffix of a phone number for matching.
 * This is the last 9 digits, which strips the country code.
 * 
 * 966501234567 → 501234567
 * +201066544750 → 066544750
 * 0501234567 → 501234567
 */
export function getPhoneSuffix(phone: string, length = 9): string {
  const digits = stripPhone(phone);
  return digits.slice(-length);
}

/**
 * Check if two phone numbers refer to the same person.
 * Compares the last 9 digits of each.
 */
export function phonesMatch(a: string, b: string): boolean {
  if (!a || !b) return false;
  return getPhoneSuffix(a) === getPhoneSuffix(b);
}

/**
 * Format a phone number for WhatsApp (digits only, no +).
 * This is what Waha expects: "966501234567@c.us"
 */
export function formatForWhatsApp(phone: string): string {
  return normalizePhone(phone);
}

/**
 * Format a phone number for display.
 * +966 50 123 4567
 */
export function formatForDisplay(phone: string): string {
  const digits = normalizePhone(phone);
  if (digits.startsWith("966") && digits.length === 12) {
    return `+${digits.slice(0, 3)} ${digits.slice(3, 5)} ${digits.slice(5, 8)} ${digits.slice(8)}`;
  }
  if (digits.startsWith("20") && digits.length === 12) {
    return `+${digits.slice(0, 2)} ${digits.slice(2, 6)} ${digits.slice(6)}`;
  }
  return `+${digits}`;
}
