/**
 * Génère un mot de passe aléatoire respectant les règles :
 * - Minuscule
 * - Majuscule
 * - Chiffre
 * - Caractère spécial
 * @param length Longueur du mot de passe, par défaut 12
 */
export function generatePassword(length: number = 12): string {
  if (length < 4) {
    throw new Error("Le mot de passe doit avoir au moins 4 caractères pour respecter toutes les règles.");
  }

  const lowers = "abcdefghijklmnopqrstuvwxyz";
  const uppers = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  const numbers = "0123456789";
  const specials = "!@#$%^&*()_+~";

  // Un caractère obligatoire de chaque catégorie
  const mandatory = [
    lowers[Math.floor(Math.random() * lowers.length)],
    uppers[Math.floor(Math.random() * uppers.length)],
    numbers[Math.floor(Math.random() * numbers.length)],
    specials[Math.floor(Math.random() * specials.length)],
  ];

  // Compléter avec des caractères aléatoires issus de tous les sets combinés
  const allChars = lowers + uppers + numbers + specials;
  const remainingLength = length - mandatory.length;
  const rest = Array.from({ length: remainingLength }, () =>
    allChars[Math.floor(Math.random() * allChars.length)]
  );

  // Mélanger le tout pour éviter que les 4 premiers caractères soient toujours fixes
  const fullPassword = [...mandatory, ...rest];
  for (let i = fullPassword.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [fullPassword[i], fullPassword[j]] = [fullPassword[j], fullPassword[i]];
  }

  return fullPassword.join("");
}
