
/**
 * DIAGNOSIS & ROOT CAUSE:
 * Supabase AuthRetryableFetchError is typically caused by:
 * 1. Network instability or ad-blockers blocking Supabase API endpoints.
 * 2. Invalid or expired refresh tokens leading to an infinite refresh loop.
 * 3. CORS misconfiguration on the Supabase project preventing the client from fetching session data.
 * 
 * FIXES IMPLEMENTED:
 * - Standardized `handleSupabaseError` to properly categorize and log these errors.
 * - Added detailed context logging including stack traces for better debugging.
 * - Created clear delineations between Network, Auth, and Unknown errors to prevent UI loops.
 */

export const handleSupabaseError = (error, context = 'Operation') => {
  console.error(`[Supabase Error] Context: ${context}`);
  console.error(`[Supabase Error] Details:`, error);
  
  if (error?.stack) {
    console.debug(`[Supabase Error] Stack Trace:`, error.stack);
  }

  let type = 'UNKNOWN_ERROR';
  let message = error?.message || 'An unexpected error occurred.';
  let isAuthError = false;

  const lowerMsg = message.toLowerCase();

  // Identify Authentication & Token Errors
  if (
    lowerMsg.includes('jwt') || 
    lowerMsg.includes('token') || 
    lowerMsg.includes('session') || 
    lowerMsg.includes('auth') ||
    lowerMsg.includes('authretryablefetcherror') ||
    error?.name === 'AuthRetryableFetchError'
  ) {
    type = 'AUTH_EXPIRED';
    isAuthError = true;
    message = 'Authentication session expired or invalid. Please log in again.';
  } 
  // Identify Network / CORS Errors
  else if (
    lowerMsg.includes('network') || 
    lowerMsg.includes('fetch') || 
    lowerMsg.includes('connection') || 
    lowerMsg.includes('failed to fetch') ||
    lowerMsg.includes('cors')
  ) {
    type = 'NETWORK_ERROR';
    message = 'Network connection issue detected. Please check your internet connection or disable ad-blockers.';
  }

  return {
    type,
    message,
    isAuthError,
    originalError: error
  };
};
