import xior, { merge } from 'xior'

const baseURL = import.meta.env.VITE_API_URL

export type THttpServer = { accessToken?: string }

export const HttpServer = (parameters?: THttpServer) => {
  const { accessToken } = 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: {
        ...(accessToken && { Authorization: `Bearer ${accessToken}` }),
      },
    })
  })

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

  return instance
}
