import axios from 'axios';
import {BASE_API_URL} from '../globalConstants';
import {removeToken} from './auth';
import {getToken,setToken} from "./auth";

export const instance = axios.create({
  baseURL: BASE_API_URL,
  headers: {
    token:getToken()
  },
  validateStatus(status) {
    return status < 400;
  },
});

instance.interceptors.request.use(config => {
  const token = getToken();
  if (token) {
    config.headers.Authorization = token;
  }
  return config;
});

instance.interceptors.response.use(response => {
  // refresh access token
  const token = response.headers?.token;
  if (token) {
    setToken(token);
  }
  return response;
});

/**
 * New Http Request Util
 * Feature:
 *  1. Support customize onFulfilled and onRejected handler
 *  2. Support default backend service response error handler
 *  3. Support redux rejected action handler @see rejectedActionMessageHandler
 * @template T
 * @param {(string | AxiosRequestConfig)} url
 * @param {AxiosRequestConfig} [config]
 * @param {{
 *     onFulfilled?: (value: AxiosResponse<any>) => APIResponse<T>;
 *     onRejected?: (error) => any;
 *   }} [extra]
 * @return {*}  {Promise<APIResponse<T>>}
 */
export function request(url,config,extra) {
  const defaultFulfilled = response => {
    const {data} = response;
    if (data?.code===200){
      return data
    }
    if (data?.code===403){
      removeToken();
    }
    throw standardErrorMessageTransformer(data);
  };

  const defaultRejected = error => {
    throw standardErrorMessageTransformer(error);
  };
  const axiosPromise =
    typeof url === 'string' ? instance(url, config) : instance(url);
  return axiosPromise
    .then(extra?.onFulfilled || defaultFulfilled, unAuthorizationErrorHandler)
    .catch(extra?.onRejected || defaultRejected);
}

function unAuthorizationErrorHandler(error) {
  const {code,msg} = error
  if (code !== 200) {
    //message.error({ key: code, content: i18next.t(`global.${code}`) });
    removeToken();
    return true;
  }
  throw msg;
}

function standardErrorMessageTransformer(error) {
  if (error?.msg) {
    return error?.msg;
  }
  return error;
}
