export const sanitizeInput = (input: string): string => {
  return input
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#039;');
};

export const validateEmail = (email: string): boolean => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
};

export const validatePassword = (password: string): boolean => {
  // 至少8个字符，包含至少一个字母和一个数字
  return password.length >= 8 && /[a-zA-Z]/.test(password) && /[0-9]/.test(password);
};

export const generateCSRFToken = (): string => {
  return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
};

export const testXSSProtection = (input: string): boolean => {
  const sanitized = sanitizeInput(input);
  return sanitized !== input;
};

export const testCSRFProtection = (): boolean => {
  const token = generateCSRFToken();
  // 模拟存储CSRF令牌
  sessionStorage.setItem('csrfToken', token);
  // 模拟验证CSRF令牌
  const storedToken = sessionStorage.getItem('csrfToken');
  return storedToken === token;
};

export const testPasswordStrength = (password: string): {
  strength: 'weak' | 'medium' | 'strong';
  message: string;
} => {
  if (password.length < 8) {
    return { strength: 'weak', message: '密码长度至少8个字符' };
  }
  if (!/[a-zA-Z]/.test(password) || !/[0-9]/.test(password)) {
    return { strength: 'weak', message: '密码必须包含至少一个字母和一个数字' };
  }
  if (/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(password)) {
    return { strength: 'strong', message: '密码强度良好' };
  }
  return { strength: 'medium', message: '密码强度一般' };
};