/**
 * Token调试工具
 * 用于诊断token相关的问题
 */

export const debugToken = () => {
  console.group('🔍 Token调试信息');
  
  // 检查环境
  console.log('1. 环境检查:');
  console.log('   - 是否在浏览器环境:', typeof window !== 'undefined');
  console.log('   - localStorage是否可用:', typeof localStorage !== 'undefined');
  
  // 检查localStorage中的token
  console.log('\n2. LocalStorage检查:');
  try {
    const token = localStorage.getItem('auth_token');
    console.log('   - auth_token存在:', !!token);
    if (token) {
      console.log('   - token长度:', token.length);
      console.log('   - token前20字符:', token.substring(0, 20) + '...');
      console.log('   - token类型:', typeof token);
    }
  } catch (error) {
    console.error('   - localStorage访问错误:', error);
  }
  
  // 检查Cookie中的token
  console.log('\n3. Cookie检查:');
  try {
    const cookies = document.cookie;
    const hasAuthToken = cookies.includes('auth_token=');
    console.log('   - Cookie中有auth_token:', hasAuthToken);
    if (hasAuthToken) {
      const tokenMatch = cookies.match(/auth_token=([^;]+)/);
      const cookieToken = tokenMatch ? tokenMatch[1] : null;
      console.log('   - Cookie token前20字符:', cookieToken?.substring(0, 20) + '...');
    }
  } catch (error) {
    console.error('   - Cookie访问错误:', error);
  }
  
  // 检查axios默认headers
  console.log('\n4. Axios配置检查:');
  import('./client').then(({ apiClient }) => {
    console.log('   - 默认baseURL:', apiClient.defaults.baseURL);
    console.log('   - 默认headers:', apiClient.defaults.headers);
    console.log('   - 拦截器数量:', {
      request: apiClient.interceptors.request.handlers?.length || 0,
      response: apiClient.interceptors.response.handlers?.length || 0
    });
  });
  
  console.groupEnd();
};

/**
 * 测试token是否正确添加到请求中
 */
export const testTokenInRequest = async () => {
  console.group('🧪 Token请求测试');
  
  try {
    const { apiClient } = await import('./client');
    
    // 创建一个测试请求（不会真正发送）
    const testConfig = {
      method: 'get',
      url: '/test',
      headers: {}
    };
    
    // 手动调用请求拦截器
    const processedConfig = apiClient.interceptors.request.handlers[0]?.fulfilled?.(testConfig);
    
    console.log('测试请求配置:');
    console.log('   - URL:', processedConfig?.url);
    console.log('   - Headers:', processedConfig?.headers);
    console.log('   - Authorization header:', processedConfig?.headers?.Authorization);
    
  } catch (error) {
    console.error('测试请求配置失败:', error);
  }
  
  console.groupEnd();
};

/**
 * 在控制台中运行的快速诊断
 */
export const quickDiagnose = () => {
  debugToken();
  setTimeout(() => {
    testTokenInRequest();
  }, 100);
};