"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var auth_exports = {};
__export(auth_exports, {
  authorize: () => authorize,
  endSession: () => endSession,
  getIDPInfoFromUrl: () => getIDPInfoFromUrl,
  isUserAuthorized: () => isUserAuthorized,
  login: () => login,
  navigateToLoginPage: () => navigateToLoginPage
});
module.exports = __toCommonJS(auth_exports);
var import_pui_analytics_so = require("@elliemae/pui-analytics-so");
var import_history = require("../history.js");
var import_auth = require("../../api/auth/index.js");
var import_users = require("../../api/users/index.js");
var import_user_session_event = require("../../analytics/user-session-event.js");
var import_logrocket = require("../logrocket.js");
var import_helper = require("./helper.js");
var import_config = require("../app-config/config.js");
var import_log_records = require("../log-records.js");
var import_loginParams = require("./loginParams.js");
var import_logger = require("../logger.js");
const IDP_ENDPOINT_CONFIG_KEY = "serviceEndpoints.idp";
const isUserAuthorized = () => !!(0, import_helper.getAuthorizationHeader)();
const getIDPInfoFromUrl = () => {
  const currentUrl = new URL(window.location.href);
  const code = currentUrl.searchParams.get("code") || "";
  const idpErrorCode = currentUrl.searchParams.get("error_code") || "";
  currentUrl.search = "";
  return { code, idpErrorCode, redirectUri: currentUrl.href };
};
const navigateToLoginPage = ({
  clientId,
  redirectUri,
  idpErrorCode,
  scope,
  // eslint-disable-next-line camelcase
  responseType
}) => {
  const idpHost = (0, import_config.getAppConfigValue)(IDP_ENDPOINT_CONFIG_KEY, "");
  const idpUrl = new URL("/authorize", idpHost);
  const idpOptions = {
    client_id: clientId,
    redirect_uri: redirectUri,
    response_type: responseType,
    scope
  };
  const searchParams = new URLSearchParams(
    idpErrorCode ? Object.assign(idpOptions, { error_code: idpErrorCode }) : idpOptions
  );
  idpUrl.search = searchParams.toString();
  window.location.replace(idpUrl.href);
};
const endSession = async ({
  clientId,
  redirectUri,
  responseType,
  scope,
  code = "",
  skipRevoke = false
}) => {
  try {
    const authorization = (0, import_helper.getAuthorizationHeader)();
    sessionStorage.clear();
    const token = authorization ? authorization.split(" ")[1] : "";
    if (!skipRevoke)
      await (0, import_auth.revokeToken)({
        clientId,
        token
      });
    (0, import_user_session_event.logoutEvent)();
    (0, import_logrocket.lrTrack)("logout");
    (0, import_pui_analytics_so.updateBAEventParameters)({ instanceId: "", userId: "" });
    const idpHost = (0, import_config.getAppConfigValue)(IDP_ENDPOINT_CONFIG_KEY, "");
    const logoutUrl = new URL("/authorize", idpHost);
    const params = {
      client_id: clientId,
      redirect_uri: redirectUri || "",
      ...code && { error_code: code },
      response_type: responseType || "",
      scope
    };
    const searchParams = new URLSearchParams(params);
    logoutUrl.search = searchParams.toString();
    window.location.replace(logoutUrl.href);
  } catch (err) {
    (0, import_logger.getLogger)()?.error({
      ...import_log_records.logRecords.LOGOUT_FAILED,
      exception: err
    });
  }
};
const authorize = async ({
  code,
  redirectUri,
  clientId,
  scope,
  responseType,
  isConsumerUser
}) => {
  try {
    const { tokenType, accessToken } = await (0, import_auth.getToken)({
      code,
      clientId,
      scope,
      redirectUri
    });
    (0, import_loginParams.setLoginParams)({ clientId, scope, responseType, redirectUri });
    const authorizationToken = `${tokenType} ${accessToken}`;
    (0, import_helper.setAuthorizationHeader)(authorizationToken);
    const introspectResponse = await (0, import_auth.introspectToken)({
      clientId,
      accessToken
    });
    sessionStorage.setItem("user", JSON.stringify(introspectResponse));
    const {
      encompass_instance_id: instanceId,
      user_name: userName,
      bearer_token: bearerToken,
      user_key: userKey
    } = introspectResponse;
    const cred = {
      bearerToken,
      realm: instanceId,
      userName,
      sessionId: bearerToken?.replace(`${instanceId} `, "")
    };
    sessionStorage.setItem("cred", JSON.stringify(cred));
    sessionStorage.setItem("instanceId", instanceId);
    sessionStorage.setItem("userId", userName);
    (0, import_user_session_event.loginEvent)({ instanceId, userId: userName });
    (0, import_pui_analytics_so.updateBAEventParameters)({ instanceId, userId: userName });
    const eventData = {
      name: userName,
      instanceId
    };
    (0, import_logrocket.lrIdentify)(userKey, eventData);
    (0, import_logrocket.lrTrack)("login", eventData);
    const data = await (0, import_users.getUser)({ userName, isConsumerUser });
    sessionStorage.setItem("userSettings", JSON.stringify(data));
    const pathName = new URL(redirectUri).pathname;
    import_history.browserHistory.replace(pathName);
  } catch (err) {
    const errCode = err?.response?.data?.code;
    await endSession({
      clientId,
      redirectUri,
      code: errCode,
      scope,
      responseType
    });
    (0, import_logger.getLogger)()?.error({
      ...import_log_records.logRecords.LOGIN_FAILED,
      exception: err
    });
  }
};
const login = async ({
  clientId,
  scope,
  responseType,
  isConsumerUser
}) => {
  const { code, idpErrorCode, redirectUri } = getIDPInfoFromUrl();
  const loginInfo = {
    clientId,
    scope,
    responseType,
    redirectUri,
    code,
    idpErrorCode,
    isConsumerUser
  };
  if (code) {
    await authorize(loginInfo);
    return { authorized: true };
  }
  navigateToLoginPage(loginInfo);
  return { authorized: false };
};
