import axios, { AxiosInstance } from 'axios';

const isExceptionRoute = (url: string) => {
  // роуты, которые ломаются, когда получают токены авторизации
  const regulars = [
    /pgs-application\/.+\/Applications\/.+\/file\//,
    /pgs-application\/.+\/Applications\/.+\/sign\//,
    // Пример: pgs-application/6b57fbf7-7910-4d07-b6e7-47be9b9af5de/Applications/d729cf65-c9db-46bb-a8e9-82ab8364dbe4/file/
  ];
  return regulars.some((el) => el.test(url));
};

export const addAuthIntercepter = (instance: AxiosInstance = axios) => {
  instance.interceptors.request.use(
    async function (config) {
      // eslint-disable-next-line @typescript-eslint/no-var-requires
      const { auth } = require('@services/AuthService');

      if (isExceptionRoute(config.url ?? '')) {
        return config;
      }
      if (auth) {
        const Authorization = await auth.getAccessToken();
        config.headers.common.Authorization = `Bearer ${Authorization}`;
      }

      return config;
    },
    function (error) {
      // Do something with request error
      return Promise.reject(error);
    }
  );
};
