/**
 * Shared input validation utilities
 * @countermeasure/web-components/utils/validation
 */

export interface ValidationResult {
  valid: boolean
  message?: string
}

export interface ValidationRule {
  validate: (value: unknown) => boolean
  message: string
}

/** Validate that a value is not empty */
export function validateRequired(value: unknown): boolean {
  if (value === null || value === undefined) return false
  if (typeof value === 'string') return value.trim().length > 0
  return true
}

/** Validate an email address format */
export function validateEmail(value: string): boolean {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)
}

/** Validate a URL format */
export function validateUrl(value: string): boolean {
  try {
    new URL(value)
    return true
  } catch {
    return false
  }
}

/** Validate minimum length */
export function validateMinLength(value: string, min: number): boolean {
  return value.length >= min
}

/** Validate maximum length */
export function validateMaxLength(value: string, max: number): boolean {
  return value.length <= max
}

/** Validate a value matches a regex pattern */
export function validatePattern(value: string, pattern: RegExp): boolean {
  return pattern.test(value)
}

/**
 * Create a composite validator from an array of rules.
 * Returns the first failing validation result, or valid if all pass.
 */
export function createValidator(rules: ValidationRule[]): (value: unknown) => ValidationResult {
  return (value: unknown): ValidationResult => {
    for (const rule of rules) {
      if (!rule.validate(value)) {
        return { valid: false, message: rule.message }
      }
    }
    return { valid: true }
  }
}
