/** Common Vuetify form validation rules */

export function required(label = '此项') {
  return (v: unknown) => !!v || `${label}不能为空`
}

export function minLength(min: number, label = '内容') {
  return (v: string) => !v || v.length >= min || `${label}至少${min}个字符`
}

export function maxLength(max: number, label = '内容') {
  return (v: string) => !v || v.length <= max || `${label}不超过${max}个字符`
}

export function isNumber(label = '值') {
  return (v: string) => !v || !isNaN(Number(v)) || `${label}必须是数字`
}

export function numberRange(min: number, max: number, label = '值') {
  return (v: string) => {
    if (!v) return true
    const n = Number(v)
    return (!isNaN(n) && n >= min && n <= max) || `${label}必须在${min}-${max}之间`
  }
}

export function ipAddress(label = 'IP地址') {
  return (v: string) => {
    if (!v) return true
    // IPv4: each octet 0-255
    const ipv4 = /^(\d{1,3}\.){3}\d{1,3}$/.test(v) && v.split('.').every(o => Number(o) <= 255)
    // IPv6: loose check for hex:colon format
    const ipv6 = /^[a-fA-F0-9:]+$/.test(v) && v.includes(':')
    // Domain/hostname
    const hostname = /^[a-zA-Z0-9.-]+$/.test(v)
    return ipv4 || ipv6 || hostname || `${label}格式不正确`
  }
}

export function cronExpression(label = 'Cron表达式') {
  return (v: string) => !v || /^[\d\s*\/,\-]+$/.test(v) || `${label}格式不正确`
}

export function matchOther(other: () => string, label = '密码') {
  return (v: string) => v === other() || `两次${label}不一致`
}
