"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SOCIAL_PROOF_TRAIT_NAME = exports.PersonalizationService = exports.PERSONALIZATION_STORAGE_SCOPE = exports.PERSONALIZATION_STORAGE_ITEM_KEY_PREFIX = exports.PERSONALIZATION_PROVIDER_PCT_TTL_MS = void 0;
exports.getCachedProviderPctMapAndRefresh = getCachedProviderPctMapAndRefresh;
exports.getProviderPctMap = void 0;
exports.getProviderPctMapSync = getProviderPctMapSync;
exports.personalizationService = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
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 _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _storageClient = require("@atlaskit/frontend-utilities/storage-client");
var _currentSiteCloudId = require("../current-site-cloud-id");
var BASE_URL = '/gateway/api/tap-delivery/api/v3/personalization';
var PERSONALIZATION_STORAGE_SCOPE = exports.PERSONALIZATION_STORAGE_SCOPE = 'smart-card-social-proof';
var PERSONALIZATION_STORAGE_ITEM_KEY_PREFIX = exports.PERSONALIZATION_STORAGE_ITEM_KEY_PREFIX = 'pct-map:v1:';
var PERSONALIZATION_PROVIDER_PCT_TTL_MS = exports.PERSONALIZATION_PROVIDER_PCT_TTL_MS = 24 * 60 * 60 * 1000;
var SOCIAL_PROOF_TRAIT_NAME = exports.SOCIAL_PROOF_TRAIT_NAME = 'sl_3p_connected_providers_site_pct';
var smartCardStorage = new _storageClient.StorageClient(PERSONALIZATION_STORAGE_SCOPE);

/** Keys written by this service in localStorage when using {@link smartCardStorage}. */
var LOCAL_STORAGE_ROW_KEY_PREFIX = "".concat(PERSONALIZATION_STORAGE_SCOPE, "_").concat(PERSONALIZATION_STORAGE_ITEM_KEY_PREFIX);
function scopedCacheKey(cloudId, traitName) {
  return "".concat(cloudId, ":").concat(traitName);
}
function pctMapStorageItemKey(cloudId, traitName) {
  return "".concat(PERSONALIZATION_STORAGE_ITEM_KEY_PREFIX).concat(encodeURIComponent(cloudId), ":").concat(encodeURIComponent(traitName));
}
function fetchSiteTraits(_x) {
  return _fetchSiteTraits.apply(this, arguments);
}
/**
 * Service for fetching site-level traits from the TAP Delivery personalization API.
 */
function _fetchSiteTraits() {
  _fetchSiteTraits = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee3(cloudId) {
    var _data$attributes;
    var response, data;
    return _regenerator.default.wrap(function _callee3$(_context3) {
      while (1) switch (_context3.prev = _context3.next) {
        case 0:
          _context3.next = 2;
          return fetch("".concat(BASE_URL, "/site/").concat(cloudId), {
            method: 'GET',
            credentials: 'include',
            headers: {
              'Content-Type': 'application/json'
            }
          });
        case 2:
          response = _context3.sent;
          if (response.ok) {
            _context3.next = 5;
            break;
          }
          return _context3.abrupt("return", []);
        case 5:
          _context3.next = 7;
          return response.json();
        case 7:
          data = _context3.sent;
          return _context3.abrupt("return", (_data$attributes = data === null || data === void 0 ? void 0 : data.attributes) !== null && _data$attributes !== void 0 ? _data$attributes : []);
        case 9:
        case "end":
          return _context3.stop();
      }
    }, _callee3);
  }));
  return _fetchSiteTraits.apply(this, arguments);
}
var PersonalizationService = exports.PersonalizationService = /*#__PURE__*/function () {
  function PersonalizationService() {
    (0, _classCallCheck2.default)(this, PersonalizationService);
    (0, _defineProperty2.default)(this, "cache", new Map());
  }
  return (0, _createClass2.default)(PersonalizationService, [{
    key: "getProviderPctMapSync",
    value: /** Pure synchronous read for an explicit cloud id / trait pair. */
    function getProviderPctMapSync(cloudId, traitName) {
      if (!cloudId) {
        return null;
      }
      return this.readStoredProviderPctMap(cloudId, traitName);
    }
  }, {
    key: "getProviderPctMap",
    value: function () {
      var _getProviderPctMap = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee2(cloudId, traitName) {
        var _this = this;
        var cacheKey, cachedPromise, promise, retryablePromise;
        return _regenerator.default.wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              if (cloudId) {
                _context2.next = 2;
                break;
              }
              return _context2.abrupt("return", undefined);
            case 2:
              cacheKey = scopedCacheKey(cloudId, traitName);
              cachedPromise = this.cache.get(cacheKey);
              if (!cachedPromise) {
                _context2.next = 6;
                break;
              }
              return _context2.abrupt("return", cachedPromise);
            case 6:
              promise = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee() {
                var traits, trait, mapped;
                return _regenerator.default.wrap(function _callee$(_context) {
                  while (1) switch (_context.prev = _context.next) {
                    case 0:
                      _context.prev = 0;
                      _context.next = 3;
                      return fetchSiteTraits(cloudId);
                    case 3:
                      traits = _context.sent;
                      trait = traits.find(function (t) {
                        return t.name === traitName;
                      });
                      mapped = _this.parseTraitValue(trait === null || trait === void 0 ? void 0 : trait.value);
                      if (mapped !== undefined) {
                        _this.writeStoredProviderPctMap(cloudId, traitName, mapped);
                      }
                      return _context.abrupt("return", mapped);
                    case 10:
                      _context.prev = 10;
                      _context.t0 = _context["catch"](0);
                      return _context.abrupt("return", undefined);
                    case 13:
                    case "end":
                      return _context.stop();
                  }
                }, _callee, null, [[0, 10]]);
              }))();
              retryablePromise = promise.finally(function () {
                _this.cache.delete(cacheKey);
              });
              this.cache.set(cacheKey, retryablePromise);
              return _context2.abrupt("return", retryablePromise);
            case 10:
            case "end":
              return _context2.stop();
          }
        }, _callee2, this);
      }));
      function getProviderPctMap(_x2, _x3) {
        return _getProviderPctMap.apply(this, arguments);
      }
      return getProviderPctMap;
    }()
  }, {
    key: "readStoredProviderPctMap",
    value: function readStoredProviderPctMap(cloudId, traitName) {
      try {
        var stored = smartCardStorage.getItem(pctMapStorageItemKey(cloudId, traitName));
        if (stored === undefined || stored === null) {
          return null;
        }
        return this.normalizeProviderPctMap(stored);
      } catch (_unused2) {
        return null;
      }
    }
  }, {
    key: "writeStoredProviderPctMap",
    value: function writeStoredProviderPctMap(cloudId, traitName, map) {
      try {
        smartCardStorage.setItemWithExpiry(pctMapStorageItemKey(cloudId, traitName), map, PERSONALIZATION_PROVIDER_PCT_TTL_MS);
      } catch (_unused3) {
        // Quota, private-mode, etc.
      }
    }
  }, {
    key: "normalizeProviderPctMap",
    value: function normalizeProviderPctMap(value) {
      if ((0, _typeof2.default)(value) !== 'object' || value === null || Array.isArray(value)) {
        return null;
      }
      var map = {};
      var entries = Object.entries(value);
      for (var _i = 0, _entries = entries; _i < _entries.length; _i++) {
        var _entries$_i = (0, _slicedToArray2.default)(_entries[_i], 2),
          providerKey = _entries$_i[0],
          percentageRaw = _entries$_i[1];
        if (typeof percentageRaw !== 'number' || !Number.isFinite(percentageRaw)) {
          return null;
        }
        map[providerKey] = percentageRaw;
      }
      return map;
    }
  }, {
    key: "parseTraitValue",
    value: function parseTraitValue(raw) {
      if (typeof raw !== 'string') {
        return undefined;
      }
      try {
        var parsed = JSON.parse(raw);
        var normalized = this.normalizeProviderPctMap(parsed);
        return normalized === null ? undefined : normalized;
      } catch (_unused4) {
        return undefined;
      }
    }
  }, {
    key: "clearCache",
    value: function clearCache() {
      this.cache.clear();
      this.clearStoredProviderPctMaps();
    }
  }, {
    key: "clearStoredProviderPctMaps",
    value: function clearStoredProviderPctMaps() {
      if (typeof globalThis.localStorage === 'undefined' || globalThis.localStorage === null) {
        return;
      }
      var keysToRemove = [];
      for (var index = 0; index < globalThis.localStorage.length; index += 1) {
        var key = globalThis.localStorage.key(index);
        if (key !== null && key.startsWith(LOCAL_STORAGE_ROW_KEY_PREFIX)) {
          keysToRemove.push(key);
        }
      }
      for (var _i2 = 0, _keysToRemove = keysToRemove; _i2 < _keysToRemove.length; _i2++) {
        var _key = _keysToRemove[_i2];
        try {
          globalThis.localStorage.removeItem(_key);
        } catch (_unused5) {
          /* ignore */
        }
      }
    }
  }]);
}();
var personalizationService = exports.personalizationService = new PersonalizationService();
var getProviderPctMap = exports.getProviderPctMap = function getProviderPctMap(cloudId, traitName) {
  return personalizationService.getProviderPctMap(cloudId, traitName);
};
function getProviderPctMapSync(cloudId, traitName) {
  return personalizationService.getProviderPctMapSync(cloudId, traitName);
}

/**
 * Backwards-compatible cache-first helper for inline-card social proof callers.
 *
 * Reads the persisted provider percentage map synchronously using the current site cloud id, then
 * starts a background refresh for subsequent mounts. The async result intentionally does not affect
 * the current call site, matching the warm-cache-only rendering contract.
 */
function getCachedProviderPctMapAndRefresh(traitName) {
  var cloudId = (0, _currentSiteCloudId.getCurrentSiteCloudIdSync)();
  var providerPctMap = getProviderPctMapSync(cloudId, traitName);
  void (0, _currentSiteCloudId.getCurrentSiteCloudId)().then(function (resolvedCloudId) {
    void getProviderPctMap(resolvedCloudId, traitName);
  });
  return providerPctMap;
}