package com.saas.shared.util;

import java.security.SecureRandom;
import java.util.regex.Pattern;

/**
 * Utility for generating secure passwords
 * Generates passwords that meet security requirements:
 * - At least 12 characters
 * - Mix of uppercase, lowercase, numbers, and special characters
 */
public class PasswordGeneratorUtil {

    private static final String UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String LOWERCASE = "abcdefghijklmnopqrstuvwxyz";
    private static final String NUMBERS = "0123456789";
    private static final String SPECIAL_CHARS = "!@#$%^&*()-_=+[]{}|;:,.<>?";
    private static final String ALL_CHARS = UPPERCASE + LOWERCASE + NUMBERS + SPECIAL_CHARS;
    private static final SecureRandom RANDOM = new SecureRandom();

    /**
     * Generate a secure password meeting security requirements
     * 
     * @return A 16-character password with uppercase, lowercase, numbers, and special characters
     */
    public static String generateSecurePassword() {
        StringBuilder password = new StringBuilder();
        
        // Ensure at least one character from each required category
        password.append(UPPERCASE.charAt(RANDOM.nextInt(UPPERCASE.length())));
        password.append(LOWERCASE.charAt(RANDOM.nextInt(LOWERCASE.length())));
        password.append(NUMBERS.charAt(RANDOM.nextInt(NUMBERS.length())));
        password.append(SPECIAL_CHARS.charAt(RANDOM.nextInt(SPECIAL_CHARS.length())));
        
        // Fill remaining characters with random selection from all characters
        for (int i = password.length(); i < 16; i++) {
            password.append(ALL_CHARS.charAt(RANDOM.nextInt(ALL_CHARS.length())));
        }
        
        // Shuffle the password to avoid predictable patterns
        return shuffleString(password.toString());
    }

    /**
     * Validate password meets requirements
     */
    public static boolean validatePassword(String password) {
        if (password == null || password.length() < 12) {
            return false;
        }
        
        boolean hasUppercase = Pattern.compile("[A-Z]").matcher(password).find();
        boolean hasLowercase = Pattern.compile("[a-z]").matcher(password).find();
        boolean hasNumbers = Pattern.compile("[0-9]").matcher(password).find();
        boolean hasSpecialChars = Pattern.compile("[!@#$%^&*()\\-_=+\\[\\]{}|;:,.<>?]").matcher(password).find();
        
        return hasUppercase && hasLowercase && hasNumbers && hasSpecialChars;
    }

    private static String shuffleString(String string) {
        char[] array = string.toCharArray();
        for (int i = array.length - 1; i > 0; i--) {
            int index = RANDOM.nextInt(i + 1);
            char temp = array[index];
            array[index] = array[i];
            array[i] = temp;
        }
        return new String(array);
    }
}
