/**
 * 校验工具函数
 */

/**
 * 校验邮箱
 */
export function isEmail(value: string): boolean {
  const reg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return reg.test(value)
}

/**
 * 校验手机号（中国大陆）
 */
export function isPhone(value: string): boolean {
  const reg = /^1[3-9]\d{9}$/
  return reg.test(value)
}

/**
 * 校验 URL
 */
export function isUrl(value: string): boolean {
  try {
    new URL(value)
    return true
  } catch {
    return false
  }
}

/**
 * 校验 IP 地址
 */
export function isIP(value: string): boolean {
  const reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
  return reg.test(value)
}

/**
 * 校验端口号
 */
export function isPort(value: string | number): boolean {
  const port = typeof value === 'string' ? parseInt(value) : value
  return !isNaN(port) && port >= 1 && port <= 65535
}

/**
 * 校验必填
 */
export function isRequired(value: any): boolean {
  if (value === null || value === undefined) return false
  if (typeof value === 'string') return value.trim().length > 0
  if (Array.isArray(value)) return value.length > 0
  return true
}

/**
 * 校验最小长度
 */
export function minLength(value: string, min: number): boolean {
  return value.length >= min
}

/**
 * 校验最大长度
 */
export function maxLength(value: string, max: number): boolean {
  return value.length <= max
}

/**
 * 校验数值范围
 */
export function inRange(value: number, min: number, max: number): boolean {
  return value >= min && value <= max
}

/**
 * 校验密码强度
 * @returns 0-4, 0=无, 1=弱, 2=中, 3=强, 4=很强
 */
export function passwordStrength(password: string): number {
  if (!password) return 0

  let strength = 0

  // 长度
  if (password.length >= 8) strength++
  if (password.length >= 12) strength++

  // 字符类型
  if (/[a-z]/.test(password)) strength++
  if (/[A-Z]/.test(password)) strength++
  if (/[0-9]/.test(password)) strength++
  if (/[^a-zA-Z0-9]/.test(password)) strength++

  return Math.min(strength, 4)
}

/**
 * 校验对象
 */
export interface ValidationRule {
  validator: (value: any) => boolean
  message: string
}

export interface ValidationResult {
  valid: boolean
  errors: string[]
}

export function validate(value: any, rules: ValidationRule[]): ValidationResult {
  const errors: string[] = []

  for (const rule of rules) {
    if (!rule.validator(value)) {
      errors.push(rule.message)
    }
  }

  return {
    valid: errors.length === 0,
    errors,
  }
}
