var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/modules/Order/utils/manualProductDiscount.ts
var manualProductDiscount_exports = {};
__export(manualProductDiscount_exports, {
  buildManualProductDiscountItem: () => buildManualProductDiscountItem,
  ensureManualProductDiscountList: () => ensureManualProductDiscountList,
  findManualProductDiscountItem: () => findManualProductDiscountItem,
  hasManualProductDiscountFlag: () => hasManualProductDiscountFlag,
  mergeManualProductDiscountIntoList: () => mergeManualProductDiscountIntoList,
  resolveManualDiscountMessage: () => resolveManualDiscountMessage,
  resolveManualDiscountOriginTotal: () => resolveManualDiscountOriginTotal,
  resolveManualDiscountReasonFromSources: () => resolveManualDiscountReasonFromSources,
  resolveSafeProductNum: () => resolveSafeProductNum,
  shouldBuildManualProductDiscount: () => shouldBuildManualProductDiscount,
  stripManualProductDiscountItems: () => stripManualProductDiscountItems,
  syncManualProductDiscountProductNum: () => syncManualProductDiscountProductNum
});
module.exports = __toCommonJS(manualProductDiscount_exports);
var import_decimal = __toESM(require("decimal.js"));
function resolveSafeProductNum(num) {
  const parsed = Number(num);
  if (!Number.isFinite(parsed) || parsed <= 0)
    return 1;
  return Math.floor(parsed);
}
function syncManualProductDiscountProductNum(discountList, productNum) {
  const quantity = resolveSafeProductNum(productNum);
  return (discountList || []).map((item) => {
    if ((item == null ? void 0 : item.type) !== "product")
      return item;
    return {
      ...item,
      discount: {
        ...item.discount || {},
        product_num: quantity
      }
    };
  });
}
function resolveManualDiscountOriginTotal(sources) {
  const candidates = [
    sources.originTotal,
    sources.extendOriginTotal,
    sources.originExtendOriginTotal,
    sources.sourceExtendOriginTotal
  ];
  for (const candidate of candidates) {
    if (candidate === void 0 || candidate === null || candidate === "")
      continue;
    const parsed = Number(candidate);
    if (Number.isFinite(parsed))
      return parsed;
  }
  const unit = Number(sources.catalogUnitPrice);
  const quantity = sources.quantity ?? 1;
  if (Number.isFinite(unit) && unit > 0) {
    return new import_decimal.default(unit).mul(quantity).toNumber();
  }
  return NaN;
}
function resolveManualDiscountReasonFromSources(sources) {
  for (const candidate of [
    sources.discountReason,
    sources.extendDiscountReason,
    sources.originExtendDiscountReason
  ]) {
    if (candidate != null && String(candidate).trim() !== "") {
      return String(candidate);
    }
  }
  return "";
}
function hasManualProductDiscountFlag(metadata) {
  if (!metadata)
    return false;
  const override = metadata.price_override;
  if (override !== void 0 && override !== null && override !== "") {
    return true;
  }
  return metadata.is_manual_discount === 1 || metadata.is_manual_discount === true;
}
function ensureManualProductDiscountList(params) {
  var _a, _b, _c, _d, _e, _f, _g, _h;
  const list = params.discountList || [];
  const quantity = resolveSafeProductNum(params.quantity);
  if (findManualProductDiscountItem(list)) {
    return syncManualProductDiscountProductNum(list, quantity);
  }
  const metadata = params.metadata || {};
  const originalNum = Number(params.originalPrice);
  const sellingNum = Number(params.sellingPrice);
  const hasPriceOverride = hasManualProductDiscountFlag(metadata);
  const shouldBuild = shouldBuildManualProductDiscount({
    hasPriceOverride,
    originTotal: originalNum,
    sellingTotal: sellingNum
  });
  if (!shouldBuild) {
    return list;
  }
  if (!Number.isFinite(originalNum) || !Number.isFinite(sellingNum) || originalNum === sellingNum) {
    return list;
  }
  const message = resolveManualDiscountMessage(
    list,
    resolveManualDiscountReasonFromSources({
      extendDiscountReason: (_b = (_a = metadata.origin) == null ? void 0 : _a._extend) == null ? void 0 : _b.discount_reason,
      originExtendDiscountReason: (_d = (_c = metadata.origin) == null ? void 0 : _c._extend) == null ? void 0 : _d.discount_reason
    })
  );
  return mergeManualProductDiscountIntoList(
    list,
    buildManualProductDiscountItem({
      originTotal: originalNum,
      sellingTotal: sellingNum,
      quantity,
      message,
      discountway: (_f = (_e = metadata.origin) == null ? void 0 : _e._extend) == null ? void 0 : _f.discountway,
      discount_per: (_h = (_g = metadata.origin) == null ? void 0 : _g._extend) == null ? void 0 : _h.discount_per
    })
  );
}
function findManualProductDiscountItem(discountList) {
  return (discountList || []).find((item) => (item == null ? void 0 : item.type) === "product");
}
function resolveManualDiscountMessage(discountList, fallback) {
  var _a, _b;
  const message = (_b = (_a = findManualProductDiscountItem(discountList)) == null ? void 0 : _a.discount) == null ? void 0 : _b.message;
  if (message != null && String(message).trim() !== "") {
    return String(message);
  }
  return fallback ?? "";
}
function stripManualProductDiscountItems(discountList) {
  return (discountList || []).filter((item) => (item == null ? void 0 : item.type) !== "product");
}
function buildManualProductDiscountItem(params) {
  const origin = new import_decimal.default(Number(params.originTotal) || 0);
  const selling = new import_decimal.default(Number(params.sellingTotal) || 0);
  const diff = origin.minus(selling);
  const quantity = resolveSafeProductNum(params.quantity);
  return {
    amount: diff.toDecimalPlaces(2).toNumber(),
    type: "product",
    discount: {
      message: params.message ?? "",
      discountway: params.discountway ?? "num",
      product_num: quantity,
      discount_per: params.discount_per ?? "",
      discount_type: diff.isNegative() ? "change_price" : "discount"
    }
  };
}
function mergeManualProductDiscountIntoList(discountList, manualItem) {
  const base = stripManualProductDiscountItems(discountList);
  if (!manualItem)
    return base;
  if (manualItem.amount === 0 && !manualItem.discount.message)
    return base;
  return [...base, manualItem];
}
function shouldBuildManualProductDiscount(params) {
  return Boolean(params.hasPriceOverride);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  buildManualProductDiscountItem,
  ensureManualProductDiscountList,
  findManualProductDiscountItem,
  hasManualProductDiscountFlag,
  mergeManualProductDiscountIntoList,
  resolveManualDiscountMessage,
  resolveManualDiscountOriginTotal,
  resolveManualDiscountReasonFromSources,
  resolveSafeProductNum,
  shouldBuildManualProductDiscount,
  stripManualProductDiscountItems,
  syncManualProductDiscountProductNum
});
