import { boot } from 'quasar/wrappers';
import axios, { AxiosInstance } from 'axios';

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $axios: AxiosInstance;
    $api: AxiosInstance;
  }
}

// Be careful when using SSR for cross-request state pollution
// due to creating a Singleton instance here;
// If any client changes this (global) instance, it might be a
// good idea to move this instance creation inside of the
// "export default () => {}" function below (which runs individually
// for each client)
const apiServer = axios.create({ baseURL: process.env.VUE_APP_API_SERVER });
apiServer.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('accesstoken');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },

  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);
apiServer.interceptors.response.use(
  (res) => {
    return res;
  },
  async (err) => {
    const originalConfig = err.config;
    const listNotRefreach = ['/auth/login-google', '/auth/login'];
    if (!listNotRefreach.includes(originalConfig.url) && err.response) {
      // Access Token was expired
      if (err.response.status === 401 && !originalConfig._retry) {
        originalConfig._retry = true;
        const tryTime = Number(localStorage.getItem('try'));
        localStorage.setItem('try', (tryTime + 1).toString());
        try {
          if (tryTime < 2) {
            const rs = await apiServer.post('auth/refresh-token', {
              refresh_token: localStorage.getItem('refresh'),
            });

            localStorage.setItem('accesstoken', rs.data.data.access_token);
            localStorage.setItem('refresh', rs.data.data.refresh_token);
            if (rs.data.data) localStorage.setItem('try', '0');

            return apiServer(originalConfig);
          } else {
            localStorage.removeItem('accesstoken');
            localStorage.removeItem('refresh');
            window.close();
          }
        } catch (_error) {
          return Promise.reject(_error);
        }
      }
    }

    return Promise.reject(err);
  }
);

export default boot(({ app }) => {
  app.config.globalProperties.$axios = axios;
  app.config.globalProperties.$apiServer = apiServer;
});

export { apiServer };
