/**
 * Password Strength Validation Utility
 * Enforces strong passwords for account security
 */

export interface PasswordValidationResult {
  valid: boolean;
  score: number; // 0-100
  feedback: string[];
  requirements: {
    minLength: boolean;
    hasUppercase: boolean;
    hasLowercase: boolean;
    hasNumber: boolean;
    hasSpecialChar: boolean;
    notCommon: boolean;
  };
}

// Common passwords to reject (top 100 most common)
const COMMON_PASSWORDS = [
  'password', 'password123', '123456', '12345678', 'qwerty', 'abc123',
  'monkey', '1234567', 'letmein', 'trustno1', 'dragon', 'baseball',
  'iloveyou', 'master', 'sunshine', 'ashley', 'bailey', 'passw0rd',
  'shadow', '123123', '654321', 'superman', 'qazwsx', 'michael',
  'football', 'welcome', 'jesus', 'ninja', 'mustang', 'password1'
];

/**
 * Validates password strength against enterprise security requirements
 *
 * Requirements:
 * - Minimum 12 characters
 * - At least 1 uppercase letter
 * - At least 1 lowercase letter
 * - At least 1 number
 * - At least 1 special character (@$!%*?&)
 * - Not in common passwords list
 *
 * @param password - Password to validate
 * @param userInfo - Optional user info to prevent password = email/name
 * @returns Validation result with score and feedback
 */
export function validatePasswordStrength(
  password: string,
  userInfo?: { email?: string; name?: string }
): PasswordValidationResult {
  const feedback: string[] = [];
  let score = 0;

  // Requirement checks
  const requirements = {
    minLength: password.length >= 12,
    hasUppercase: /[A-Z]/.test(password),
    hasLowercase: /[a-z]/.test(password),
    hasNumber: /\d/.test(password),
    hasSpecialChar: /[@$!%*?&]/.test(password),
    notCommon: !COMMON_PASSWORDS.includes(password.toLowerCase()),
  };

  // Calculate score (each requirement = 16.66 points)
  if (requirements.minLength) score += 17;
  if (requirements.hasUppercase) score += 17;
  if (requirements.hasLowercase) score += 17;
  if (requirements.hasNumber) score += 17;
  if (requirements.hasSpecialChar) score += 16;
  if (requirements.notCommon) score += 16;

  // Bonus points for extra length
  if (password.length >= 16) score += 5;
  if (password.length >= 20) score += 5;

  // Generate feedback
  if (!requirements.minLength) {
    feedback.push('Password must be at least 12 characters long');
  }
  if (!requirements.hasUppercase) {
    feedback.push('Password must contain at least one uppercase letter (A-Z)');
  }
  if (!requirements.hasLowercase) {
    feedback.push('Password must contain at least one lowercase letter (a-z)');
  }
  if (!requirements.hasNumber) {
    feedback.push('Password must contain at least one number (0-9)');
  }
  if (!requirements.hasSpecialChar) {
    feedback.push('Password must contain at least one special character (@$!%*?&)');
  }
  if (!requirements.notCommon) {
    feedback.push('This password is too common. Please choose a more unique password.');
  }

  // Check if password contains email or name
  if (userInfo?.email && password.toLowerCase().includes(userInfo.email.split('@')[0].toLowerCase())) {
    feedback.push('Password should not contain your email address');
    score = Math.max(0, score - 20);
  }
  if (userInfo?.name && password.toLowerCase().includes(userInfo.name.toLowerCase())) {
    feedback.push('Password should not contain your name');
    score = Math.max(0, score - 20);
  }

  // Check for repeating characters
  if (/(.)\1{2,}/.test(password)) {
    feedback.push('Password contains too many repeating characters');
    score = Math.max(0, score - 10);
  }

  // Check for sequential characters
  if (/abc|bcd|cde|123|234|345|456|567|678|789/i.test(password)) {
    feedback.push('Password contains sequential characters');
    score = Math.max(0, score - 10);
  }

  // Cap score at 100
  score = Math.min(100, score);

  const valid = Object.values(requirements).every(req => req === true);

  return {
    valid,
    score,
    feedback,
    requirements,
  };
}

/**
 * Get password strength level as a string
 */
export function getPasswordStrengthLevel(score: number): 'weak' | 'fair' | 'good' | 'strong' | 'excellent' {
  if (score < 40) return 'weak';
  if (score < 60) return 'fair';
  if (score < 80) return 'good';
  if (score < 95) return 'strong';
  return 'excellent';
}

/**
 * Get password strength color for UI
 */
export function getPasswordStrengthColor(score: number): string {
  if (score < 40) return 'red';
  if (score < 60) return 'orange';
  if (score < 80) return 'yellow';
  if (score < 95) return 'green';
  return 'emerald';
}

/**
 * Bilingual feedback messages
 */
export function getPasswordFeedbackBilingual(
  feedback: string[],
  lang: 'ar' | 'en'
): string[] {
  if (lang === 'en') return feedback;

  const translations: Record<string, string> = {
    'Password must be at least 12 characters long': 'يجب أن تكون كلمة المرور 12 حرفًا على الأقل',
    'Password must contain at least one uppercase letter (A-Z)': 'يجب أن تحتوي كلمة المرور على حرف كبير واحد على الأقل (A-Z)',
    'Password must contain at least one lowercase letter (a-z)': 'يجب أن تحتوي كلمة المرور على حرف صغير واحد على الأقل (a-z)',
    'Password must contain at least one number (0-9)': 'يجب أن تحتوي كلمة المرور على رقم واحد على الأقل (0-9)',
    'Password must contain at least one special character (@$!%*?&)': 'يجب أن تحتوي كلمة المرور على رمز خاص واحد على الأقل (@$!%*?&)',
    'This password is too common. Please choose a more unique password.': 'كلمة المرور هذه شائعة جدًا. يرجى اختيار كلمة مرور أكثر تفردًا.',
    'Password should not contain your email address': 'يجب ألا تحتوي كلمة المرور على عنوان بريدك الإلكتروني',
    'Password should not contain your name': 'يجب ألا تحتوي كلمة المرور على اسمك',
    'Password contains too many repeating characters': 'تحتوي كلمة المرور على أحرف متكررة كثيرة',
    'Password contains sequential characters': 'تحتوي كلمة المرور على أحرف متتالية',
  };

  return feedback.map(msg => translations[msg] || msg);
}
