import axios from 'axios'
import { ElMessage } from 'element-plus'

const api = axios.create({
  // Use absolute URL if in docker/dev environment where frontend and backend are on different ports
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000/api/v1',
  timeout: 5000
})

api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => Promise.reject(error)
)

api.interceptors.response.use(
  (response) => {
    // Check for token renewal header
    const newToken = response.headers['x-new-token']
    if (newToken) {
      localStorage.setItem('token', newToken)
    }
    return response
  },
  (error) => {
    // Allow skipping global error handling for specific requests
    if (error.config?.skipGlobalErrorHandler) {
      return Promise.reject(error)
    }

    const message = error.response?.data?.detail || 'An error occurred'
    ElMessage.error(message)
    const authErrors = ['Could not validate credentials', 'Not authenticated', 'Invalid token type']
    if (error.response?.status === 401 || (error.response?.status === 403 && authErrors.includes(error.response?.data?.detail))) {
      localStorage.removeItem('token')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

export default api
