import axios from 'axios'
import { handleUnauthorized, isAuthRedirectInProgress } from '@/shared/utils/authRedirect'

const api = axios.create({
  baseURL: import.meta.env.BASE_URL + 'api/reports',
  headers: { 'Content-Type': 'application/json' }
})

// Request interceptor for auth token
api.interceptors.request.use((config) => {
  // Skip requests if we're already redirecting to login
  if (isAuthRedirectInProgress()) {
    const controller = new AbortController()
    controller.abort()
    config.signal = controller.signal
    return config
  }

  const token = localStorage.getItem('access_token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

// Response interceptor for error handling
api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      // Use shared handler to prevent race conditions
      handleUnauthorized()
    }
    return Promise.reject(error)
  }
)

/**
 * Helper for GET requests that include cache metadata
 * Returns response data with cache_hit, response_time_ms, cache_source fields
 *
 * @param {string} url - API endpoint path
 * @param {object} options - Axios request config (params, etc.)
 * @returns {Promise<object>} Response data with cache metadata
 */
export const getWithCacheInfo = async (url, options = {}) => {
  const response = await api.get(url, {
    ...options,
    headers: {
      ...options.headers,
      'X-Include-Cache-Metadata': 'true',
    },
  })
  return response.data
}

export default api
