import axios from "axios";
import { getLoginParams } from "../../utils/auth/loginParams.js";
import { httpClientProps } from "./props.js";
const HTTP_UNAUTHORIZED = 401;
let unAuthorizedFailureHandler = null;
const onAuthorizationFailure = (callback) => {
  unAuthorizedFailureHandler = callback;
};
const handleSuccess = (response) => response;
const handleFailure = (error) => {
  const { status } = (error || {}).response || {};
  if (status === HTTP_UNAUTHORIZED) {
    if (unAuthorizedFailureHandler && typeof unAuthorizedFailureHandler === "function") {
      return unAuthorizedFailureHandler(error).then((authorizationHeader) => {
        const { config } = error;
        if (!config?.headers) throw error;
        config.headers["Authorization"] = authorizationHeader;
        return new Promise((resolve, reject) => {
          axios.request(config).then(resolve).catch(reject);
        });
      }).catch((exception) => Promise.reject(exception));
    }
    if (httpClientProps.endSession) {
      return httpClientProps.endSession({ ...getLoginParams(), skipRevoke: true }).then(() => Promise.reject(error)).catch(() => Promise.reject(error));
    }
  }
  return Promise.reject(error);
};
export {
  handleFailure,
  handleSuccess,
  onAuthorizationFailure
};
