import axios from 'axios'

// Create axios instance with base URL
const api = axios.create({
  baseURL: '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// Add request interceptor to include authentication token
api.interceptors.request.use(
  config => {
    // Add authentication token if available
    const token = localStorage.getItem('authToken') || sessionStorage.getItem('authToken')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// Add response interceptor to handle authentication errors
api.interceptors.response.use(
  response => response,
  error => {
    // Don't log 401 errors for auth status checks (expected when not logged in)
    if (error.response && error.response.status === 401 && 
        !error.config.url.includes('/auth.php?action=status')) {
      console.error('API Error:', error)
    }
    
    // Handle 401 Unauthorized responses
    if (error.response && error.response.status === 401) {
      // Clear any stored auth data
      localStorage.removeItem('authToken')
      sessionStorage.removeItem('authToken')
      sessionStorage.removeItem('currentUser')
      
      // Emit custom event for app to handle
      window.dispatchEvent(new CustomEvent('auth-expired', {
        detail: { message: 'Session expired. Please login again.' }
      }))
    }
    
    return Promise.reject(error)
  }
)

export default api
