/**
 * Phone Number Validator
 *
 * Lenient validation that accepts various international phone formats
 * without being overly strict about the exact format.
 *
 * Created: 2025-11-18
 * Reason: validator.isMobilePhone() was too strict and caused false negatives
 *
 * Accepted Formats:
 * - +974 1234 5678 (with country code and spaces)
 * - +974-1234-5678 (with dashes)
 * - 974 1234 5678 (country code without +)
 * - 1234 5678 (local number only)
 * - +974 (12) 345 678 (with parentheses)
 * - Any combination of spaces, dashes, parentheses
 */

export interface PhoneValidationResult {
  isValid: boolean;
  error?: string;
  digitsCount?: number;
  hasCountryCode?: boolean;
}

/**
 * Validate phone number with lenient rules
 *
 * Rules:
 * 1. Must contain 5-15 digits (5 minimum for short local numbers)
 * 2. Must start with + or a digit
 * 3. Can contain spaces, dashes, parentheses for formatting
 * 4. Cannot contain letters or other special characters
 *
 * @param phoneNumber - The phone number to validate
 * @returns Validation result with error details if invalid
 */
export function validatePhoneNumber(phoneNumber: string | null | undefined): PhoneValidationResult {
  // Allow empty/null (field is optional)
  if (!phoneNumber || !phoneNumber.trim()) {
    return { isValid: true };
  }

  const trimmed = phoneNumber.trim();

  const digitsOnly = trimmed.replace(/\D/g, '');

  // Rule 1: Must contain 5-15 digits (5 minimum for short local numbers)
  if (digitsOnly.length < 5) {
    return {
      isValid: false,
      error: 'Phone number must contain at least 5 digits',
      digitsCount: digitsOnly.length,
    };
  }

  if (digitsOnly.length > 15) {
    return {
      isValid: false,
      error: 'Phone number cannot exceed 15 digits',
      digitsCount: digitsOnly.length,
    };
  }

  // Rule 2: Must start with + or digit
  if (!trimmed.match(/^[+\d]/)) {
    return {
      isValid: false,
      error: 'Phone number must start with + or a digit',
    };
  }

  // Rule 3: Should only contain allowed characters
  // Allowed: digits, +, space, dash, parentheses
  if (!trimmed.match(/^[+\d\s\-()]+$/)) {
    return {
      isValid: false,
      error: 'Phone number can only contain digits, +, spaces, dashes, and parentheses',
    };
  }

  // Rule 4: + can only appear at the start
  const plusCount = (trimmed.match(/\+/g) || []).length;
  if (plusCount > 1) {
    return {
      isValid: false,
      error: 'Only one + sign allowed (at the beginning)',
    };
  }

  if (plusCount === 1 && !trimmed.startsWith('+')) {
    return {
      isValid: false,
      error: '+ sign must be at the beginning',
    };
  }

  // All validation passed
  return {
    isValid: true,
    digitsCount: digitsOnly.length,
    hasCountryCode: trimmed.startsWith('+'),
  };
}

/**
 * Format phone number for display
 * Preserves user's formatting preference
 *
 * @param phoneNumber - The phone number to format
 * @returns The original number (we preserve user's format)
 */
export function formatPhoneNumber(phoneNumber: string | null | undefined): string {
  if (!phoneNumber) return '';
  return phoneNumber.trim();
}

/**
 * Get phone number validation error message in user's language
 *
 * @param result - Validation result
 * @param isArabic - Whether to return Arabic message
 * @returns Error message in appropriate language
 */
export function getPhoneValidationError(
  result: PhoneValidationResult,
  isArabic: boolean = false
): string | null {
  if (result.isValid) return null;

  const errorMap: Record<string, { en: string; ar: string }> = {
    'Phone number must contain at least 5 digits': {
      en: 'Phone number must contain at least 5 digits',
      ar: 'يجب أن يحتوي رقم الهاتف على 5 أرقام على الأقل',
    },
    'Phone number cannot exceed 15 digits': {
      en: 'Phone number cannot exceed 15 digits',
      ar: 'لا يمكن أن يتجاوز رقم الهاتف 15 رقماً',
    },
    'Phone number must start with + or a digit': {
      en: 'Phone number must start with + or a digit',
      ar: 'يجب أن يبدأ رقم الهاتف بـ + أو رقم',
    },
    'Phone number can only contain digits, +, spaces, dashes, and parentheses': {
      en: 'Phone number can only contain digits, +, spaces, dashes, and parentheses',
      ar: 'يمكن أن يحتوي رقم الهاتف على أرقام و + ومسافات وشرطات وأقواس فقط',
    },
  };

  const errorKey = result.error || 'Invalid phone number';
  const mapping = errorMap[errorKey];

  if (mapping) {
    return isArabic ? mapping.ar : mapping.en;
  }

  return result.error || (isArabic ? 'رقم هاتف غير صالح' : 'Invalid phone number');
}

/**
 * Example valid phone numbers for testing/documentation
 */
export const VALID_PHONE_EXAMPLES = {
  international: ['+974 1234 5678', '+971 50 123 4567', '+966 11 234 5678'],
  withDashes: ['+974-1234-5678', '974-1234-5678', '1234-5678'],
  withParentheses: ['+974 (12) 345 678', '(050) 123 4567'],
  local: ['1234 5678', '12345678'],
  minimal: ['12345', '12345678901234'], // 5-14 digits
};

/**
 * Example invalid phone numbers for testing
 */
export const INVALID_PHONE_EXAMPLES = {
  tooShort: ['1234', '123'], // Less than 5 digits
  tooLong: ['1234567890123456'], // More than 15 digits
  invalidChars: ['+974-TEST-3711', 'call me', '123abc456'],
  invalidFormat: ['++974123456', '974+123456', '-1234567'],
};
