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

export enum PasswordValidationType {
  Match,
  Different
}

export function passwordValidator(matchTo: string, validationType: PasswordValidationType): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    if (!control.parent || !control.parent.get(matchTo)) {
      return null; // parent or matching control not found
    }

    const matchToControl = control.parent.get(matchTo);

    // Depending on the validation type, return the appropriate error
    switch (validationType) {
      case PasswordValidationType.Match:
        return control.value === matchToControl?.value ? null : { passwordMismatch: true };
      case PasswordValidationType.Different:
        return control.value !== matchToControl?.value ? null : { passwordsSame: true };
      default:
        return null;
    }
  };
}
