import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';

export interface PasswordRules {
  digit?: boolean;
  specialCharacter?: boolean;
  lowerCase?: boolean;
  upperCase?: boolean;
}

export interface PasswordRuleError {
  failed: Array<keyof PasswordRules>;
}

const RULE_PATTERNS: Record<keyof PasswordRules, RegExp> = {
  digit: /[0-9]/,
  specialCharacter: /[!@#$%^&*()+_\-=}{[\]|:;"/?.><,`~]/,
  lowerCase: /[a-z]/,
  upperCase: /[A-Z]/,
};

export const passwordRulesValidator = (rules: PasswordRules): ValidatorFn => {
  return (control: AbstractControl): ValidationErrors | null => {
    const value = control.value;
    if (typeof value !== 'string' || value.length === 0) return null;

    const failed: Array<keyof PasswordRules> = [];
    for (const rule of Object.keys(rules) as Array<keyof PasswordRules>) {
      if (rules[rule] && !RULE_PATTERNS[rule].test(value)) {
        failed.push(rule);
      }
    }

    return failed.length > 0 ? { passwordRule: { failed } as PasswordRuleError } : null;
  };
};
