import xior, { merge } from 'xior'

const baseURL = import.meta.env.VITE_API_URL

type THttpClient = { token?: string }
const HttpClient = (parameters?: THttpClient) => {
  const { token } = parameters || {}
  const instance = xior.create({
    baseURL,
  })
  instance.interceptors.request.use((config) => {
    // eslint-disable-next-line no-console
    console.info(`🚀requesting ${config.url}`)

    return merge(config, {
      headers: {
        ...(token && { Authorization: `Bearer ${token}` }),
      },
    })
  })

  instance.interceptors.response.use(
    (response) => {
      return response
    },
    (error) => {
      return Promise.reject(error)
    },
  )

  return instance
}

export default HttpClient
