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

/**
 * Email validation pattern that matches standard email format.
 * More strict than HTML5 default email validation.
 */
const EMAIL_PATTERN = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

/**
 * Custom email validator that provides stricter validation than Angular's built-in.
 * Validates format: local@domain.tld
 *
 * @returns ValidatorFn that returns null if valid, or { email: true } if invalid
 *
 * @example
 * ```typescript
 * this.form = this.fb.group({
 *   email: ['', [Validators.required, emailValidator()]]
 * });
 * ```
 */
export function emailValidator(): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    if (!control.value) {
      return null; // Let required validator handle empty values
    }
    const isValid = EMAIL_PATTERN.test(control.value);
    return isValid ? null : { email: true };
  };
}
