"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getCurrentSiteCloudIdLocalStorageKey = exports.getCurrentSiteCloudId = exports.currentSiteCloudIdService = exports.CurrentSiteCloudIdService = exports.CURRENT_SITE_CLOUD_ID_TTL_MS = exports.CURRENT_SITE_CLOUD_ID_STORAGE_ITEM_KEY_PREFIX = exports.CURRENT_SITE_CLOUD_ID_LOCAL_STORAGE_KEY = void 0;
exports.getCurrentSiteCloudIdSync = getCurrentSiteCloudIdSync;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _storageClient = require("@atlaskit/frontend-utilities/storage-client");
var _linkingCommon = require("@atlaskit/linking-common");
var SMART_CARD_STORAGE_SCOPE = 'smart-card-social-proof';
var CURRENT_SITE_CLOUD_ID_STORAGE_ITEM_KEY_PREFIX = exports.CURRENT_SITE_CLOUD_ID_STORAGE_ITEM_KEY_PREFIX = 'site-cloud-id:v1:';
var CURRENT_SITE_CLOUD_ID_TTL_MS = exports.CURRENT_SITE_CLOUD_ID_TTL_MS = 24 * 60 * 60 * 1000;
var smartCardStorage = new _storageClient.StorageClient(SMART_CARD_STORAGE_SCOPE);
function normalizeBaseUri() {
  var baseUriWithNoTrailingSlash = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  return baseUriWithNoTrailingSlash.replace(/\/$/, '');
}
function cloudIdStorageItemKey() {
  var baseUriWithNoTrailingSlash = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  return "".concat(CURRENT_SITE_CLOUD_ID_STORAGE_ITEM_KEY_PREFIX).concat(encodeURIComponent(normalizeBaseUri(baseUriWithNoTrailingSlash)));
}

/** Keys written by this service in localStorage when using {@link smartCardStorage}. */
var getCurrentSiteCloudIdLocalStorageKey = exports.getCurrentSiteCloudIdLocalStorageKey = function getCurrentSiteCloudIdLocalStorageKey() {
  var baseUriWithNoTrailingSlash = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  return "".concat(SMART_CARD_STORAGE_SCOPE, "_").concat(cloudIdStorageItemKey(baseUriWithNoTrailingSlash));
};

/** Backwards-compatible default-scope key for existing tests and external assertions. */
var CURRENT_SITE_CLOUD_ID_LOCAL_STORAGE_KEY = exports.CURRENT_SITE_CLOUD_ID_LOCAL_STORAGE_KEY = getCurrentSiteCloudIdLocalStorageKey();
var CurrentSiteCloudIdService = exports.CurrentSiteCloudIdService = /*#__PURE__*/function () {
  function CurrentSiteCloudIdService() {
    (0, _classCallCheck2.default)(this, CurrentSiteCloudIdService);
    (0, _defineProperty2.default)(this, "tenantInfoInflightPromises", new Map());
  }
  return (0, _createClass2.default)(CurrentSiteCloudIdService, [{
    key: "readStoredCloudId",
    value: function readStoredCloudId() {
      var baseUriWithNoTrailingSlash = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
      try {
        var cloudId = smartCardStorage.getItem(cloudIdStorageItemKey(baseUriWithNoTrailingSlash));
        if (typeof cloudId !== 'string' || !cloudId || cloudId === 'undefined') {
          return undefined;
        }
        return cloudId;
      } catch (_unused) {
        return undefined;
      }
    }
  }, {
    key: "writeStoredCloudId",
    value: function writeStoredCloudId(baseUriWithNoTrailingSlash, cloudId) {
      if (!cloudId) {
        return;
      }
      try {
        smartCardStorage.setItemWithExpiry(cloudIdStorageItemKey(baseUriWithNoTrailingSlash), cloudId, CURRENT_SITE_CLOUD_ID_TTL_MS);
      } catch (_unused2) {
        // Quota, private-mode, SSR, etc. — same intent as personalization-service.
      }
    }
  }, {
    key: "ensureTenantInfoInflightStarted",
    value: function ensureTenantInfoInflightStarted(baseUriWithNoTrailingSlash) {
      var _this = this;
      var baseUri = normalizeBaseUri(baseUriWithNoTrailingSlash);
      var existing = this.tenantInfoInflightPromises.get(baseUri);
      if (existing) {
        return existing;
      }
      var promise = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee() {
        var response, cloudId;
        return _regenerator.default.wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              _context.prev = 0;
              _context.next = 3;
              return (0, _linkingCommon.request)('get', "".concat(baseUri, "/_edge/tenant_info"));
            case 3:
              response = _context.sent;
              cloudId = response === null || response === void 0 ? void 0 : response.cloudId;
              if (cloudId) {
                _this.writeStoredCloudId(baseUri, cloudId);
              }
              return _context.abrupt("return", cloudId ? cloudId : _this.readStoredCloudId(baseUri));
            case 9:
              _context.prev = 9;
              _context.t0 = _context["catch"](0);
              return _context.abrupt("return", _this.readStoredCloudId(baseUri));
            case 12:
              _context.prev = 12;
              _this.tenantInfoInflightPromises.delete(baseUri);
              return _context.finish(12);
            case 15:
            case "end":
              return _context.stop();
          }
        }, _callee, null, [[0, 9, 12, 15]]);
      }))();
      this.tenantInfoInflightPromises.set(baseUri, promise);
      return promise;
    }

    /** Pure synchronous read scoped to the given base URI. */
  }, {
    key: "getStoredCloudId",
    value: function getStoredCloudId() {
      var baseUriWithNoTrailingSlash = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
      return this.readStoredCloudId(baseUriWithNoTrailingSlash);
    }

    /** Writes tenant cloud id for tests or callers that intentionally warm storage before edge resolves. */
  }, {
    key: "persistStoredCloudId",
    value: function persistStoredCloudId(cloudId) {
      var baseUriWithNoTrailingSlash = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
      this.writeStoredCloudId(baseUriWithNoTrailingSlash, cloudId);
    }
  }, {
    key: "get",
    value: function () {
      var _get = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee2() {
        var baseUriWithNoTrailingSlash,
          fromStorage,
          _args2 = arguments;
        return _regenerator.default.wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              baseUriWithNoTrailingSlash = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : '';
              fromStorage = this.readStoredCloudId(baseUriWithNoTrailingSlash);
              if (!fromStorage) {
                _context2.next = 4;
                break;
              }
              return _context2.abrupt("return", fromStorage);
            case 4:
              return _context2.abrupt("return", this.ensureTenantInfoInflightStarted(baseUriWithNoTrailingSlash));
            case 5:
            case "end":
              return _context2.stop();
          }
        }, _callee2, this);
      }));
      function get() {
        return _get.apply(this, arguments);
      }
      return get;
    }() /** Clears session pin and persisted storage so the next {@link get} is a fresh tenant_info fetch. */
  }, {
    key: "clearCache",
    value: function clearCache() {
      this.tenantInfoInflightPromises.clear();
    }
  }]);
}();
var currentSiteCloudIdService = exports.currentSiteCloudIdService = new CurrentSiteCloudIdService();
function getCurrentSiteCloudIdSync() {
  var baseUriWithNoTrailingSlash = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  return currentSiteCloudIdService.getStoredCloudId(baseUriWithNoTrailingSlash);
}
var getCurrentSiteCloudId = exports.getCurrentSiteCloudId = function getCurrentSiteCloudId() {
  var baseUriWithNoTrailingSlash = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  return currentSiteCloudIdService.get(baseUriWithNoTrailingSlash);
};