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

/**
 * Validator function to check if a control's value is a valid EAN (European Article Number).
 * A valid EAN is a 13-digit number.
 *
 * @param {AbstractControl} control - The form control to validate
 * @returns {ValidationErrors | null} Returns an error object if the value is invalid, otherwise null
 */
export const eanValidator: ValidatorFn = (
  control: AbstractControl,
): ValidationErrors | null => {
  const value = control.value;
  if (value && !EAN_REGEX.test(value)) {
    return { invalidEan: true };
  }
  return null;
};

/**
 * Checks if a value is a valid EAN (European Article Number).
 * A valid EAN is a 13-digit number.
 *
 * @param {string | undefined} value - The value to check
 * @returns {boolean} True if the value is a valid EAN, false otherwise
 */
export const isEan = (value: string | undefined): boolean => {
  if (!value) {
    return false;
  }
  return EAN_REGEX.test(value);
};
