import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
import _createClass from "@babel/runtime/helpers/createClass";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import { StorageClient } from '@atlaskit/frontend-utilities/storage-client';
import { request } from '@atlaskit/linking-common';
var SMART_CARD_STORAGE_SCOPE = 'smart-card-social-proof';
export var CURRENT_SITE_CLOUD_ID_STORAGE_ITEM_KEY_PREFIX = 'site-cloud-id:v1:';
export var CURRENT_SITE_CLOUD_ID_TTL_MS = 24 * 60 * 60 * 1000;
var smartCardStorage = new 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}. */
export var 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. */
export var CURRENT_SITE_CLOUD_ID_LOCAL_STORAGE_KEY = getCurrentSiteCloudIdLocalStorageKey();
export var CurrentSiteCloudIdService = /*#__PURE__*/function () {
  function CurrentSiteCloudIdService() {
    _classCallCheck(this, CurrentSiteCloudIdService);
    _defineProperty(this, "tenantInfoInflightPromises", new Map());
  }
  return _createClass(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 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
        var response, cloudId, _t;
        return _regeneratorRuntime.wrap(function (_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              _context.prev = 0;
              _context.next = 1;
              return request('get', "".concat(baseUri, "/_edge/tenant_info"));
            case 1:
              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 2:
              _context.prev = 2;
              _t = _context["catch"](0);
              return _context.abrupt("return", _this.readStoredCloudId(baseUri));
            case 3:
              _context.prev = 3;
              _this.tenantInfoInflightPromises.delete(baseUri);
              return _context.finish(3);
            case 4:
            case "end":
              return _context.stop();
          }
        }, _callee, null, [[0, 2, 3, 4]]);
      }))();
      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 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
        var baseUriWithNoTrailingSlash,
          fromStorage,
          _args2 = arguments;
        return _regeneratorRuntime.wrap(function (_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 = 1;
                break;
              }
              return _context2.abrupt("return", fromStorage);
            case 1:
              return _context2.abrupt("return", this.ensureTenantInfoInflightStarted(baseUriWithNoTrailingSlash));
            case 2:
            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();
    }
  }]);
}();
export var currentSiteCloudIdService = new CurrentSiteCloudIdService();
export function getCurrentSiteCloudIdSync() {
  var baseUriWithNoTrailingSlash = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  return currentSiteCloudIdService.getStoredCloudId(baseUriWithNoTrailingSlash);
}
export var getCurrentSiteCloudId = function getCurrentSiteCloudId() {
  var baseUriWithNoTrailingSlash = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  return currentSiteCloudIdService.get(baseUriWithNoTrailingSlash);
};