import Axios, { InternalAxiosRequestConfig } from 'axios'
import Cookies from 'js-cookie'
import { toast } from 'react-toastify'
import { NetworkStore } from '../components/ErrorBoundary/GlobalNetworkLoadingIndicator'

const sessionKey = Cookies.get('campx_session_key')
const tenantId =
  Cookies.get('campx_tenant') ?? window.location.hostname.split('.')[0]
const institutionId =
  Cookies.get('campx_institution') ?? window.location.pathname.split('/')[1]
const openPaymentsKey = Cookies.get('campx_open_payments_key')

const isProduction = process.env.NODE_ENV === 'production'

export const formatParams = (params) => {
  return Object.fromEntries(
    Object.entries(params ?? {})?.map((i) => [
      i[0],
      i[1] === '__empty__' ? '' : i[1],
    ]),
  )
}

console.log(institutionId, sessionKey, 'test')

let axios = Axios.create({
  baseURL: process.env.REACT_APP_API_HOST,
  withCredentials: true,
  headers: {
    'x-tenant-id': tenantId,
    'x-institution-code': institutionId,
    campx_session_key: sessionKey,
  },
})

axios.interceptors.request.use(
  function (config: InternalAxiosRequestConfig) {
    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)
  },
)

axios.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 axios

export const axiosErrorToast = (error: any, fallback?: string) => {
  const fallbackMessage = fallback ?? 'Something went wrong.'
  const errorMessage =
    typeof error?.response?.data?.message !== 'string'
      ? error?.response?.data?.message?.join('\n') ?? fallbackMessage
      : error?.response?.data?.message

  return toast.error(errorMessage)
}
