import { AbstractControl, ValidatorFn, Validators } from '@angular/forms';
import { UiValidators } from '@ui/validators';

// RFC 5322 Official Standard
const emailRegexPattern =
  /^(?=.{1,254}$)(?=.{1,64}@)[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/;

export const emailNotificationValidator: ValidatorFn = (control: AbstractControl) => {
  if (control.parent) {
    const notificationChannel = control.parent.get('selected').value;
    if (notificationChannel & 1) {
      return Validators.required(control) ?? Validators.pattern(emailRegexPattern)(control);
    }
  }

  return null;
};

export const mobileNotificationValidator: ValidatorFn = (control: AbstractControl) => {
  if (control.parent) {
    const notificationChannel = control.parent.get('selected').value;
    if (notificationChannel & 2) {
      return Validators.required(control) ?? UiValidators.phone(control);
    }
  }
  return null;
};
