import Axios from 'axios'
import Cookies from 'js-cookie'
import { NetworkStore } from '../components/ErrorBoundary/GlobalNetworkLoadingIndicator'
import { isDevelopment } from '../constants'
import { formatParams } from './axios'

// const sessionKey = Cookies.get('campx_session_key')
const clientId = window.location.pathname.split('/')[1] ?? 'campx_dev'
const evaluatorKey = Cookies.get('campx_evaluator_key')

const axiosEvaluator = Axios.create({
  baseURL: process.env.REACT_APP_API_HOST,
  withCredentials: true,
  headers: {
    'x-tenant-id': clientId,
    ...(evaluatorKey && {
      campx_evaluator_key: evaluatorKey,
    }),
  },
})

axiosEvaluator.interceptors.request.use(
  function (config) {
    const params = formatParams(config?.params)
    NetworkStore.update((s) => {
      s.loading = true
    })
    return { ...config, params }
  },
  function (error) {
    NetworkStore.update((s) => {
      s.loading = false
    })
    return Promise.reject(error)
  },
)

axiosEvaluator.interceptors.response.use(
  function (response) {
    NetworkStore.update((s) => {
      s.loading = false
    })
    return response
  },
  function (err) {
    NetworkStore.update((s) => {
      s.loading = false
    })
    return Promise.reject(err)
  },
)

export default axiosEvaluator
