import axios, { AxiosInstance, AxiosError } from 'axios'

const apiClient: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_URL || 'http://localhost:8000',
  headers: {
    'Content-Type': 'application/json',
  },
  timeout: 30000,
})

apiClient.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('admin_token')
    if (token) {
      config.headers['X-Admin-Token'] = token
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

apiClient.interceptors.response.use(
  (response) => response,
  (error: AxiosError) => {
    if (error.response?.status === 401) {
      console.warn('Authentication required. Please set admin_token in localStorage.')
      // Don't redirect to avoid infinite loop
      // User should manually set: localStorage.setItem('admin_token', 'your-token')
    }

    if (error.response?.status === 429) {
      console.error('Rate limit exceeded')
    }

    return Promise.reject(error)
  }
)

export default apiClient
