"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
var BaseConfig = {
  earlyRefresh: 30
};

var getAuthorizationHeader = function getAuthorizationHeader(token) {
  return "Bearer ".concat(token);
};
/**
 * Requests a short term token from the DDB Auth API using the Cobalt session cookie to authorize the user
 * @param {string} authUrl The URL to the cobalt-token auth endpoint
 * @param {boolean} throwOnHttpStatusError Option to transform error status codes (4xx/5xx) to exceptions
 * @returns {Promise<object>} A promise that resolves to the JSON object returned by the Auth API
 */


var getShortTermToken = function getShortTermToken(_ref) {
  var _ref$authUrl = _ref.authUrl,
      authUrl = _ref$authUrl === void 0 ? 'https://auth-service.dndbeyond.com/v1/cobalt-token' : _ref$authUrl,
      _ref$throwOnHttpStatu = _ref.throwOnHttpStatusError,
      throwOnHttpStatusError = _ref$throwOnHttpStatu === void 0 ? true : _ref$throwOnHttpStatu;
  return fetch(authUrl, {
    credentials: 'include',
    method: 'POST'
  }).then(function (response) {
    // eslint-disable-next-line no-magic-numbers, `Copied from https://github.com/whatwg/fetch/issues/18#issuecomment-68273579`
    if (throwOnHttpStatusError && response.status >= 400 && response.status < 600) {
      throw new Error('Bad response from server');
    }

    return response.json();
  });
};
/**
 * Makes a getter function that will return a promise that resolves to a short term token (JWT) if signed in, null otherwise
 * @param {object} options Options object that is passed on to internally called methods
 * @returns {function(): (Promise<object>)} A promise that resolves to a short term token (JWT) if signed in, null otherwise
 */


var makeGetShortTermToken = function makeGetShortTermToken(options) {
  var _options$earlyRefresh = options.earlyRefresh,
      earlyRefresh = _options$earlyRefresh === void 0 ? BaseConfig.earlyRefresh : _options$earlyRefresh,
      _options$getShortTerm = options.getShortTermTokenFunc,
      getShortTermTokenFunc = _options$getShortTerm === void 0 ? getShortTermToken : _options$getShortTerm;
  var timeOfRequest;
  var lastSessionToken;
  var timeToLive = 0;
  var pendingRequest = null;
  return function () {
    var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
        _ref2$ignoreAnonymous = _ref2.ignoreAnonymousTimeToLive,
        ignoreAnonymousTimeToLive = _ref2$ignoreAnonymous === void 0 ? false : _ref2$ignoreAnonymous;

    if (pendingRequest) {
      return pendingRequest;
    }

    var shouldUseTimeToLive = ignoreAnonymousTimeToLive ? lastSessionToken != null : true;

    if (shouldUseTimeToLive && timeToLive && timeOfRequest + timeToLive > Date.now()) {
      return new Promise(function (resolve) {
        return resolve(lastSessionToken);
      });
    }

    timeOfRequest = Date.now();
    pendingRequest = getShortTermTokenFunc(options).then(function (data) {
      lastSessionToken = data.token; // eslint-disable-next-line no-magic-numbers, "multiply by 1000 because TTL is measured in seconds"

      timeToLive = (data.ttl - earlyRefresh) * 1000;
      pendingRequest = null;
      return data.token;
    })["catch"](function (error) {
      timeToLive = 0;
      lastSessionToken = null;
      pendingRequest = null;
      throw error;
    });
    return pendingRequest;
  };
};
/**
 * Makes a getter function that will return a promise that resolves to auth headers if signed in, an empty object otherwise
 * @param {object} options Options object that is passed on to internally called methods
 * @param {function} options.madeGetShortTermToken Optional function to use instead of calling makeGetShortTermToken so the same function instance can be shared
 * @returns {function(): (Promise<object>)} A promise that resolves to a headers object if signed in, an empty object otherwise
 */


var makeGetAuthorizationHeaders = function makeGetAuthorizationHeaders(options) {
  var getShortTermTokenFunc = options.madeGetShortTermToken || makeGetShortTermToken(options);
  return function () {
    return getShortTermTokenFunc.apply(void 0, arguments).then(function (shortTermToken) {
      if (!shortTermToken) {
        return {};
      }

      return {
        Authorization: getAuthorizationHeader(shortTermToken)
      };
    });
  };
};

var _default = {
  makeGetShortTermToken: makeGetShortTermToken,
  makeGetAuthorizationHeaders: makeGetAuthorizationHeaders
};
exports["default"] = _default;