function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
var _excluded = ["_promotionTags"];
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
import { resolveLocalizedText } from "./resolveLocalizedText";

/**
 * 评估器协议（仅本工具用到的字段）。
 * 完整定义在 `pisell_os/src/solution/BaseSales/utils/cartPromotion.ts`；
 * 这里以结构性子集约束，避免对 OS 包的硬依赖。
 */

/**
 * 给商品列表追加 `_promotionTags`，供 ProductCard 渲染。
 *
 * - 没有适用策略的商品会清除 `_promotionTags`（避免脏数据）
 * - 与 OS `cartPromotion.appendPromotionTags` 等价，仅用于 SDK Product Context
 *   把 evaluator 评估结果就近写到对外的商品列表
 *
 * @example
 * const enriched = appendPromotionTagsForProducts(products, evaluator);
 */
export function appendPromotionTagsForProducts(products, evaluator) {
  if (!Array.isArray(products) || products.length === 0 || !evaluator) {
    return products || [];
  }
  var evaluatorInput = products.map(function (item, index) {
    var _ref, _id, _product_variant_id, _price, _quantity;
    return {
      id: index,
      product_id: Number((_ref = (_id = item === null || item === void 0 ? void 0 : item.id) !== null && _id !== void 0 ? _id : item === null || item === void 0 ? void 0 : item.product_id) !== null && _ref !== void 0 ? _ref : 0) || 0,
      product_variant_id: Number((_product_variant_id = item === null || item === void 0 ? void 0 : item.product_variant_id) !== null && _product_variant_id !== void 0 ? _product_variant_id : 0) || 0,
      name: (item === null || item === void 0 ? void 0 : item.title) || (item === null || item === void 0 ? void 0 : item.name) || '',
      price: Number((_price = item === null || item === void 0 ? void 0 : item.price) !== null && _price !== void 0 ? _price : 0) || 0,
      quantity: Number((_quantity = item === null || item === void 0 ? void 0 : item.quantity) !== null && _quantity !== void 0 ? _quantity : 1) || 1,
      bundle: []
    };
  });
  var strategies;
  try {
    strategies = evaluator.getProductsApplicableStrategies({
      products: evaluatorInput
    }, false);
  } catch (error) {
    console.warn('[SalesSdk] appendPromotionTagsForProducts: evaluator 调用失败', error);
    return products;
  }
  return products.map(function (item, index) {
    var data = strategies[index];
    var tags = [];
    if (data !== null && data !== void 0 && data.hasApplicableStrategy) {
      var _iterator = _createForOfIteratorHelper(data.applicableStrategies),
        _step;
      try {
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          var strategy = _step.value;
          if (strategy.display) {
            tags.push({
              text: resolveLocalizedText(strategy.display.text),
              type: strategy.display.type,
              strategyId: strategy.strategyId
            });
          }
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }
    }
    if (tags.length === 0) {
      var _ref2 = item,
        _promotionTags = _ref2._promotionTags,
        rest = _objectWithoutProperties(_ref2, _excluded);
      void _promotionTags;
      return rest;
    }
    return _objectSpread(_objectSpread({}, item), {}, {
      _promotionTags: tags
    });
  });
}