import axios from 'axios'

// Get API base URL from environment variable or use default
// The .env file should contain: VITE_API_URL=http://127.0.0.1:8000
// Alternatively, Vite proxy can be used (configured in vite.config.ts) by setting VITE_API_URL to empty string
const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://127.0.0.1:8000'

export const apiClient = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
})

// Add token to requests
apiClient.interceptors.request.use((config) => {
  const token = localStorage.getItem('access_token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

// Handle 401 errors and network errors
apiClient.interceptors.response.use(
  (response) => response,
  (error) => {
    // Handle network errors (no response from server)
    if (!error.response && (error.message === 'Network Error' || error.code === 'ERR_NETWORK')) {
      // Check if user is logged in
      const token = localStorage.getItem('access_token')
      if (!token) {
        // Not logged in - redirect to login
        const isLoginPage = window.location.pathname === '/login'
        if (!isLoginPage) {
          window.location.href = '/login'
          return Promise.reject(error)
        }
      }
      // If logged in but network error, it's a connection issue
      console.error('Network Error:', error)
    }
    
    // Handle 401 Unauthorized
    if (error.response?.status === 401) {
      // Don't redirect if we're already on the login page (prevents clearing error messages)
      const isLoginPage = window.location.pathname === '/login'
      
      // Always clear tokens on 401, but only redirect if not already on login page
      localStorage.removeItem('access_token')
      localStorage.removeItem('refresh_token')
      // Clear sessionStorage settings on authentication failure
      sessionStorage.removeItem('identify_settings')
      
      // Only redirect if not already on login page
      if (!isLoginPage) {
        window.location.href = '/login'
      }
      // If on login page, just reject the error so the login component can handle it
    }
    return Promise.reject(error)
  }
)

export default apiClient

