import axios from 'axios'

const client = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL ?? '/api',
})

if (import.meta.env.DEV) {
  client.interceptors.request.use((config) => {
    console.debug('[ops-platform][HTTP] request', {
      method: config.method?.toUpperCase(),
      url: config.baseURL ? `${config.baseURL}${config.url ?? ''}` : config.url,
      params: config.params,
    })
    return config
  })
  client.interceptors.response.use((res) => {
    console.debug('[ops-platform][HTTP] response', {
      status: res.status,
      url: res.config.url,
    })
    return res
  })
}

client.interceptors.request.use((config) => {
  const token = localStorage.getItem('ops_token')
  if (token) config.headers.Authorization = `Bearer ${token}`
  return config
})

client.interceptors.response.use(
  (res) => res,
  (err) => {
    if (err.response?.status === 401) {
      localStorage.removeItem('ops_token')
      window.location.href = '/login'
    }
    return Promise.reject(err)
  }
)

export default client
