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

export interface ArrayMinLengthError {
  requiredLength: number;
  actualLength: number;
}

export const arrayMinLengthValidator = (min: number): ValidatorFn => {
  return (control: AbstractControl): ValidationErrors | null => {
    const value = control.value;
    const actualLength = Array.isArray(value) ? value.length : 0;

    if (!Array.isArray(value) || actualLength < min) {
      return {
        arrayMinLength: { requiredLength: min, actualLength } as ArrayMinLengthError,
      };
    }

    return null;
  };
};
