import axios from 'axios'
import { getToken } from '~/assets/scripts/auth'

axios.defaults.baseURL = '/'
axios.defaults.headers.common['Content-Type'] = 'application/json'
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'
axios.defaults.withCredentials = true

export const fetcher = async (APIUrl, httpVerb = 'POST', payload) => {
  axios.defaults.headers.common.Authorization = getToken()
  const axiosConfig = {
    method: httpVerb.toLowerCase(),
    url: APIUrl,
    data: payload,
  }
  return await axios(axiosConfig)
    .then(function (response) {
      if (response.data.code === 200) {
        return response.data
      } else {
        return Promise.reject(response)
      }
    })
    .catch(function (error) {
      // if (error.data.code === 401) {
      //   window.location.href = "/login"
      // } else if (error.data.code === 407) {
      //   window.location.href = "/login"
      // } else {
      //   return Promise.reject(error.data.msg)
      // }
      console.log(error)
    })
}
