import { authService } from '../services/authService';

export const debugAuth = async () => {
  console.log('🔍 Debugging authentication...');
  
  try {
    // Check if user is authenticated
    const isAuthenticated = authService.isAuthenticated();
    console.log('🔍 Is authenticated:', isAuthenticated);
    
    if (isAuthenticated) {
      // Get current user
      const user = authService.getCurrentUser();
      console.log('🔍 Current user:', user);
      
      // Get token
      const token = await authService.getToken();
      console.log('🔍 Token available:', !!token);
      console.log('🔍 Token length:', token?.length);
      console.log('🔍 Token preview:', token ? `${token.substring(0, 20)}...` : 'No token');
      
      // Test token format
      if (token) {
        const parts = token.split('.');
        console.log('🔍 Token parts:', parts.length);
        if (parts.length === 3) {
          try {
            const header = JSON.parse(atob(parts[0]));
            const payload = JSON.parse(atob(parts[1]));
            console.log('🔍 Token header:', header);
            console.log('🔍 Token payload:', {
              iss: payload.iss,
              aud: payload.aud,
              auth_time: payload.auth_time,
              exp: payload.exp,
              iat: payload.iat,
              user_id: payload.user_id,
              email: payload.email
            });
            
            // Check if token is expired
            const now = Math.floor(Date.now() / 1000);
            const isExpired = payload.exp && payload.exp < now;
            console.log('🔍 Token expired:', isExpired);
            console.log('🔍 Current time:', now);
            console.log('🔍 Token expires:', payload.exp);
          } catch (error) {
            console.error('🔍 Error parsing token:', error);
          }
        }
      }
    } else {
      console.log('🔍 User is not authenticated');
    }
  } catch (error) {
    console.error('🔍 Auth debug error:', error);
  }
};

// Export a function to test API authentication
export const testAPIAuth = async () => {
  console.log('🧪 Testing API authentication...');
  
  try {
    const token = await authService.getToken();
    if (!token) {
      console.log('❌ No token available');
      return false;
    }
    
    console.log('🔐 Token available, length:', token.length);
    console.log('🔐 Token preview:', token.substring(0, 20) + '...');
    console.log('🔐 Token format check:', token.split('.').length === 3 ? 'Valid JWT format' : 'Invalid format');
    
    // Test the API endpoint
    const response = await fetch(`${import.meta.env.VITE_API_BASE_URL}/documents`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
    });
    
    console.log('🧪 API response status:', response.status);
    console.log('🧪 API response headers:', Object.fromEntries(response.headers.entries()));
    
    if (response.ok) {
      const data = await response.json();
      console.log('✅ API authentication successful');
      console.log('🧪 Response data:', data);
      return true;
    } else {
      const errorText = await response.text();
      console.log('❌ API authentication failed');
      console.log('🧪 Error response:', errorText);
      
      // Try to parse error as JSON
      try {
        const errorJson = JSON.parse(errorText);
        console.log('❌ Error details:', errorJson);
      } catch {
        console.log('❌ Raw error:', errorText);
      }
      return false;
    }
  } catch (error) {
    console.error('❌ API test error:', error);
    return false;
  }
}; 