import axios from 'axios'
import router from './router'

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


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


api.interceptors.response.use(
  (response) => {
    return response
  },
  async (error) => {
    const originalRequest = error.config
    

    if (error.response?.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true
      

      localStorage.removeItem('token')
      localStorage.removeItem('user')

      router.push('account/auth/login')
      
      return Promise.reject(error)
    }

    if (error.response?.status === 403) {
      router.push('/unauthorized')
    }
    
    return Promise.reject(error)
  }
)

export default api