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

/**
 * Name validation options.
 */
export interface NameValidatorOptions {
  /** Minimum length required (default: 3) */
  minLength?: number;
  /** Maximum length allowed (default: 100) */
  maxLength?: number;
  /** Whether to allow numbers (default: false) */
  allowNumbers?: boolean;
}

const DEFAULT_OPTIONS: Required<NameValidatorOptions> = {
  minLength: 3,
  maxLength: 100,
  allowNumbers: false,
};

/**
 * Custom name validator with configurable options.
 * Validates that name contains only letters, spaces, and common punctuation.
 *
 * @param options - Validation options
 * @returns ValidatorFn that returns validation errors or null
 *
 * @example
 * ```typescript
 * this.form = this.fb.group({
 *   name: ['', [Validators.required, nameValidator({ minLength: 2 })]]
 * });
 * ```
 */
export function nameValidator(options: NameValidatorOptions = {}): ValidatorFn {
  const opts = { ...DEFAULT_OPTIONS, ...options };

  return (control: AbstractControl): ValidationErrors | null => {
    if (!control.value) {
      return null; // Let required validator handle empty values
    }

    const value = control.value.trim();

    if (value.length < opts.minLength) {
      return { minlength: { requiredLength: opts.minLength, actualLength: value.length } };
    }

    if (value.length > opts.maxLength) {
      return { maxlength: { requiredLength: opts.maxLength, actualLength: value.length } };
    }

    // Pattern: letters (including accented), spaces, hyphens, apostrophes
    const pattern = opts.allowNumbers
      ? /^[a-zA-ZáéíóúÁÉÍÓÚñÑüÜ0-9\s'-]+$/
      : /^[a-zA-ZáéíóúÁÉÍÓÚñÑüÜ\s'-]+$/;

    if (!pattern.test(value)) {
      return { pattern: true };
    }

    return null;
  };
}
