import axios from "axios"
import router from "../router";
import store from "../store";
import {getSecurityKey} from "../helper";


const axiosClient = axios.create({
  baseURL: API_BASE_URL
});

const actionScope = `loading`;

let requestsPending = 0;

const req = {
  pending: () => {
    requestsPending++;
    store.dispatch('auth/setLoader', true)
  },
  done: () => {
    requestsPending--;
    store.dispatch('auth/setLoader', false)
  }
};
axiosClient.interceptors.request.use(function (config) {
  req.pending();

  const security_key = getSecurityKey();

  if(security_key) {
      config.headers['security-key'] = security_key;
  }
/*  const token = getToken();

  config.headers.Authorization = 'Bearer ' + token;
  config.headers['Content-Type'] = 'application/json';
  config.headers['Accept'] = 'application/json';
  config.headers['Permission-Version'] = store.getters['auth/user']?.permission_version;*/
  console.log('resquest.success', config);
  //console.log('request loader_status', store.getters['auth/getLoaderStatus']);

  return config;

}, function (error) {
  req.done();
  console.log('resquest.error', error);
  return Promise.reject(error);
});

axiosClient.interceptors.response.use(
  response => {
    req.done();
    console.log('response.success', response);
    console.log('response loader_status', store.getters['auth/getLoaderStatus']);

    return response.data;
  },
  async error => {
    req.done();
    console.log('resquest.error', error);

    var originalRequest = error.config;

    /*if (error.response.status == 500) {
      router.push({ name: 'error-500' })
    } else if (error.response.status == 401 && !originalRequest._retry) {


      if (getRefreshToken()) {
        const response = await store.dispatch('auth/authenticateWithRefreshToken')
        if (isApiSuccess(response)) {
          originalRequest._retry = true;
          return axiosClient(originalRequest);
        }
      }

      store.dispatch('auth/logout')
      router.push({ name: 'error-401' })
    }*/

    return Promise.reject(error);
  }
);

export default axiosClient
