/**
 * Form validation utilities
 */

// Email validation
export const validateEmail = (email: string): { valid: boolean; message?: string } => {
  if (!email) {
    return { valid: false, message: '邮箱不能为空' };
  }

  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(email)) {
    return { valid: false, message: '请输入有效的邮箱地址' };
  }

  return { valid: true };
};

// Phone validation (支持中国大陆手机号)
export const validatePhone = (phone: string): { valid: boolean; message?: string } => {
  if (!phone) {
    return { valid: true }; // Phone is optional
  }

  // 中国大陆手机号：1开头，第二位3-9，共11位
  const phoneRegex = /^1[3-9]\d{9}$/;
  if (!phoneRegex.test(phone)) {
    return { valid: false, message: '请输入有效的手机号码（11位）' };
  }

  return { valid: true };
};

// Employee ID validation
export const validateEmployeeId = (employeeId: string): { valid: boolean; message?: string } => {
  if (!employeeId) {
    return { valid: true }; // Employee ID is optional
  }

  // 只允许字母、数字、下划线、连字符，长度 2-20
  const employeeIdRegex = /^[a-zA-Z0-9_-]{2,20}$/;
  if (!employeeIdRegex.test(employeeId)) {
    return { valid: false, message: '员工编号只能包含字母、数字、下划线、连字符（2-20位）' };
  }

  return { valid: true };
};

// Username validation
export const validateUsername = (username: string): { valid: boolean; message?: string } => {
  if (!username) {
    return { valid: false, message: '用户名不能为空' };
  }

  if (username.length < 3 || username.length > 32) {
    return { valid: false, message: '用户名长度应为 3-32 个字符' };
  }

  // 只允许字母、数字、下划线
  const usernameRegex = /^[a-zA-Z0-9_]+$/;
  if (!usernameRegex.test(username)) {
    return { valid: false, message: '用户名只能包含字母、数字、下划线' };
  }

  return { valid: true };
};

// Password strength validation
export const validatePassword = (password: string): { 
  valid: boolean; 
  message?: string;
  strength?: 'weak' | 'medium' | 'strong';
} => {
  if (!password) {
    return { valid: false, message: '密码不能为空' };
  }

  if (password.length < 8) {
    return { valid: false, message: '密码至少需要 8 个字符', strength: 'weak' };
  }

  // Check password strength
  const hasUpperCase = /[A-Z]/.test(password);
  const hasLowerCase = /[a-z]/.test(password);
  const hasNumber = /\d/.test(password);
  const hasSpecialChar = /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/.test(password);

  const strengthCount = [hasUpperCase, hasLowerCase, hasNumber, hasSpecialChar].filter(Boolean).length;

  if (strengthCount < 2) {
    return { 
      valid: false, 
      message: '密码需要包含大写字母、小写字母、数字中的至少两种',
      strength: 'weak'
    };
  }

  const strength = strengthCount === 2 ? 'medium' : strengthCount >= 3 ? 'strong' : 'weak';

  return { valid: true, strength };
};

// Department code validation
export const validateDepartmentCode = (code: string): { valid: boolean; message?: string } => {
  if (!code) {
    return { valid: false, message: '部门编码不能为空' };
  }

  // 只允许大写字母、数字、下划线，长度 2-32
  const codeRegex = /^[A-Z0-9_]{2,32}$/;
  if (!codeRegex.test(code)) {
    return { valid: false, message: '部门编码只能包含大写字母、数字、下划线（2-32位）' };
  }

  return { valid: true };
};

// Position code validation
export const validatePositionCode = (code: string): { valid: boolean; message?: string } => {
  if (!code) {
    return { valid: false, message: '岗位编码不能为空' };
  }

  // 只允许大写字母、数字、下划线，长度 2-32
  const codeRegex = /^[A-Z0-9_]{2,32}$/;
  if (!codeRegex.test(code)) {
    return { valid: false, message: '岗位编码只能包含大写字母、数字、下划线（2-32位）' };
  }

  return { valid: true };
};

// Role code validation
export const validateRoleCode = (code: string): { valid: boolean; message?: string } => {
  if (!code) {
    return { valid: false, message: '角色编码不能为空' };
  }

  // 只允许大写字母、数字、下划线，长度 2-64
  const codeRegex = /^[A-Z0-9_]{2,64}$/;
  if (!codeRegex.test(code)) {
    return { valid: false, message: '角色编码只能包含大写字母、数字、下划线（2-64位）' };
  }

  return { valid: true };
};

// Generic required field validation
export const validateRequired = (value: any, fieldName: string = '该字段'): { valid: boolean; message?: string } => {
  if (value === null || value === undefined || value === '') {
    return { valid: false, message: `${fieldName}不能为空` };
  }
  return { valid: true };
};

// Debounced validation helper (for async validation like uniqueness check)
export const createDebouncedValidator = (
  validatorFn: (...args: any[]) => Promise<any>,
  delay: number = 500
) => {
  let timeoutId: NodeJS.Timeout;

  return (...args: any[]) => {
    return new Promise((resolve) => {
      clearTimeout(timeoutId);
      timeoutId = setTimeout(async () => {
        const result = await validatorFn(...args);
        resolve(result);
      }, delay);
    });
  };
};

