/**
 * Auth Redirect Utility
 *
 * Handles 401 Unauthorized responses with protection against race conditions.
 * When multiple API calls return 401 simultaneously, only the first one
 * triggers the redirect to prevent UI flickering and double redirects.
 */

// Flag to prevent multiple simultaneous redirects
let isRedirecting = false

/**
 * Handle 401 Unauthorized error by clearing auth data and redirecting to login.
 * Uses a flag to prevent race conditions when multiple API calls fail simultaneously.
 *
 * @returns {boolean} true if redirect was initiated, false if already redirecting
 */
export function handleUnauthorized() {
  // Prevent multiple redirects
  if (isRedirecting) {
    console.log('[Auth] Redirect already in progress, skipping...')
    return false
  }

  isRedirecting = true
  console.log('[Auth] 401 Unauthorized - clearing auth data and redirecting to login')

  // Clear all auth-related data from localStorage
  localStorage.removeItem('access_token')
  localStorage.removeItem('refresh_token')
  localStorage.removeItem('user')

  // Small delay to ensure localStorage is cleared before redirect
  // This also allows any pending API calls to complete/fail gracefully
  setTimeout(() => {
    window.location.href = import.meta.env.BASE_URL + 'login'
  }, 100)

  return true
}

/**
 * Check if a redirect is currently in progress.
 * Useful for components that want to skip error handling during redirect.
 *
 * @returns {boolean} true if redirect is in progress
 */
export function isAuthRedirectInProgress() {
  return isRedirecting
}

/**
 * Reset the redirect flag.
 * Should only be used in tests or special cases.
 */
export function resetAuthRedirectFlag() {
  isRedirecting = false
}
