import axios from 'axios'

const instance = axios.create({
  baseURL: '/api',
  timeout: 8000
})

let token: string | null = null

instance.interceptors.request.use((config) => {
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

instance.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      console.warn('Sessão expirada, por favor, faça login novamente.')
    }
    return Promise.reject(error)
  }
)

export const apiClient = {
  get: instance.get,
  post: instance.post,
  put: instance.put,
  delete: instance.delete,
  setToken: (value: string | null) => {
    token = value
  }
}
