import type { AxiosError, AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from 'axios'
import axios, { isAxiosError } from 'axios'

const axiosInstance: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 5000,
})

axiosInstance.defaults.headers.common['Content-Type'] = 'application/json'

axiosInstance.interceptors.request.use(
  function (config: InternalAxiosRequestConfig) {
    const token = localStorage.getItem('access_token')
    if (token && config.headers) config.headers['Authorization'] = token
    return config
  },
  function (error) {
    console.log(error.response)
    return Promise.reject(error)
  },
)

axiosInstance.interceptors.response.use(
  function (response: AxiosResponse) {
    return response
  },
  function (error) {
    if (isAxiosError<AxiosError>(error)) {
      // console.log('axios error', error.response?.data)
    }

    return Promise.reject(error)
  },
)

export default axiosInstance
