import { getLocale } from '@arcblock/ux/lib/Locale/context';
// eslint-disable-next-line import/no-extraneous-dependencies
import { createAxios } from '@blocklet/js-sdk';
import isNull from 'lodash/isNull';

import { getPrefix } from './util';

const api = createAxios();

api.interceptors.request.use(
  (config: any) => {
    const prefix = getPrefix();
    config.baseURL = prefix || '';
    const locale = getLocale(window.blocklet?.languages);
    const query = new URLSearchParams(config.url?.split('?').pop());
    config.params = { ...(config.params || {}), locale };
    const authToken = window.__PAYMENT_KIT_AUTH_TOKEN;
    if (authToken && typeof config.params.authToken === 'undefined' && !query.has('authToken')) {
      config.params.authToken = authToken;
    }
    // If we do not have livemode neither in config nor in query params, we will use the value from localStorage
    if (typeof config.params.livemode === 'undefined' && query.has('livemode') === false) {
      const livemode = localStorage.getItem('livemode');
      config.params.livemode = isNull(livemode) ? true : JSON.parse(livemode);
    }

    return config;
  },
  (err: any) => Promise.reject(err)
);

export default api;
