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/solution/BaseSales/utils.ts
var utils_exports = {};
__export(utils_exports, {
  buildProductLineFingerprint: () => buildProductLineFingerprint,
  createEmptySummary: () => createEmptySummary,
  getSafeProductNum: () => getSafeProductNum,
  isSkuOnlyDeleteIdentity: () => isSkuOnlyDeleteIdentity,
  normalizeOrderProduct: () => normalizeOrderProduct
});
module.exports = __toCommonJS(utils_exports);
var import_decimal = __toESM(require("decimal.js"));
var import_utils = require("../../modules/Order/utils");
var import_manualProductDiscount = require("../../modules/Order/utils/manualProductDiscount");
function createEmptySummary() {
  return {
    product_quantity: 0,
    product_original_amount: "0.00",
    product_amount: "0.00",
    product_expect_amount: "0.00",
    product_tax_fee: "0.00",
    shipping_fee: "0.00",
    shipping_tax_fee: "0.00",
    tax_fee: "0.00",
    surcharge_fee: "0.00",
    discount_amount: "0.00",
    deposit_amount: "0.00",
    expect_amount: "0.00",
    total_amount: "0.00",
    amount_gap: "0.00",
    rounding_amount: "0.00",
    pay_service_charge_amount: "0.00"
  };
}
function buildProductLineFingerprint(productOptionItem, productBundle) {
  const optArr = Array.isArray(productOptionItem) ? productOptionItem : [];
  const normalizedOpts = optArr.map((item) => ({
    option_group_item_id: Number(item == null ? void 0 : item.option_group_item_id) || 0,
    option_group_id: Number(item == null ? void 0 : item.option_group_id) || 0,
    num: typeof (item == null ? void 0 : item.num) === "number" && !Number.isNaN(item.num) ? Math.max(1, Math.floor(item.num)) : 1,
    price: String((item == null ? void 0 : item.price) ?? "")
  })).sort((p, q) => {
    if (p.option_group_item_id !== q.option_group_item_id) {
      return p.option_group_item_id - q.option_group_item_id;
    }
    if (p.option_group_id !== q.option_group_id)
      return p.option_group_id - q.option_group_id;
    if (p.num !== q.num)
      return p.num - q.num;
    return p.price.localeCompare(q.price);
  });
  const bundleArr = Array.isArray(productBundle) ? productBundle : [];
  const normalizedBundles = bundleArr.map((item) => ({
    bundle_id: Number((item == null ? void 0 : item.bundle_id) ?? (item == null ? void 0 : item.id) ?? 0) || 0,
    product_id: Number(item == null ? void 0 : item.product_id) || 0,
    num: typeof (item == null ? void 0 : item.num) === "number" && !Number.isNaN(item.num) ? Math.max(1, Math.floor(item.num)) : 1
  })).sort((p, q) => {
    if (p.bundle_id !== q.bundle_id)
      return p.bundle_id - q.bundle_id;
    if (p.product_id !== q.product_id)
      return p.product_id - q.product_id;
    return p.num - q.num;
  });
  return JSON.stringify([normalizedOpts, normalizedBundles]);
}
function getSafeProductNum(num) {
  if (!num || Number.isNaN(num))
    return 1;
  if (num < 1)
    return 1;
  return Math.floor(num);
}
function isSkuOnlyDeleteIdentity(x) {
  if (x.identity_key)
    return false;
  return !("product_option_item" in x) && !("product_bundle" in x);
}
function normalizeOrderProduct(product) {
  var _a, _b, _c, _d, _e, _f;
  const metadata = { ...product.metadata || {} };
  const resolvedIdentityKey = ((_a = product.metadata) == null ? void 0 : _a.unique_identification_number) ? String(product.metadata.unique_identification_number) : product.unique_identification_number && String(product.unique_identification_number).length > 0 ? String(product.unique_identification_number) : product.identity_key && String(product.identity_key).length > 0 ? String(product.identity_key) : (0, import_utils.createUuidV4)();
  metadata.unique_identification_number = resolvedIdentityKey;
  const priceOverride = metadata.price_override;
  const originOtherBundle = (_d = (_c = (_b = metadata.origin) == null ? void 0 : _b._extend) == null ? void 0 : _c.other) == null ? void 0 : _d.bundle;
  let bundleInput = product.product_bundle || [];
  if (priceOverride !== void 0 && priceOverride !== null && priceOverride !== "" && Array.isArray(originOtherBundle) && originOtherBundle.length > 0) {
    const priceById = /* @__PURE__ */ new Map();
    originOtherBundle.forEach((item) => {
      if ((item == null ? void 0 : item.id) == null)
        return;
      const unit = item.price ?? item.bundle_selling_price;
      if (unit === void 0 || unit === null)
        return;
      priceById.set(String(item.id), String(unit));
    });
    const base = Array.isArray(bundleInput) && bundleInput.length > 0 ? bundleInput : originOtherBundle;
    bundleInput = base.map((item) => {
      const unit = priceById.get(String(item == null ? void 0 : item.id));
      if (unit === void 0)
        return item;
      return {
        ...item,
        price: unit,
        bundle_selling_price: unit
      };
    });
  }
  const normalizedBundle = bundleInput.map((item) => ({
    ...item,
    bundle_id: item.bundle_id ?? item.id,
    bundle_product_id: item.bundle_product_id ?? item._bundle_product_id,
    bundle_group_id: item.bundle_group_id ?? item.group_id,
    bundle_selling_price: item.bundle_selling_price ?? item.price ?? "0.00",
    price: item.price ?? item.custom_price ?? item.bundle_selling_price ?? "0.00",
    price_type: item.price_type ?? item.custom_price_type ?? "",
    price_type_ext: item.price_type_ext ?? item.custom_price_type_ext ?? ""
  }));
  const normalizedOptions = product.product_option_item || [];
  const optionSum = (0, import_utils.sumOptionUnitPrice)(normalizedOptions);
  const isV2 = metadata.price_schema_version === 2 || metadata.price_schema_version === "2";
  const variantId = Number(product.product_variant_id || 0);
  const variantList = variantId ? (_e = metadata == null ? void 0 : metadata.origin) == null ? void 0 : _e.variant : null;
  const variantPrice = Array.isArray(variantList) ? (_f = variantList.find((v) => Number(v == null ? void 0 : v.id) === variantId)) == null ? void 0 : _f.price : void 0;
  const resolvedSource = (() => {
    var _a2, _b2;
    if (metadata.source_product_price !== void 0) {
      return String(metadata.source_product_price);
    }
    if (variantPrice !== void 0 && variantPrice !== null) {
      return String(variantPrice);
    }
    const originPrice = (_a2 = product._origin) == null ? void 0 : _a2.price;
    if (originPrice !== void 0 && originPrice !== null) {
      return String(originPrice);
    }
    const originBasePrice = (_b2 = product._origin) == null ? void 0 : _b2.base_price;
    if (originBasePrice !== void 0 && originBasePrice !== null) {
      return String(originBasePrice);
    }
    if (!isV2 && metadata.main_product_original_price !== void 0) {
      return String(metadata.main_product_original_price);
    }
    return product.original_price ?? product.selling_price ?? "0.00";
  })();
  const mainOriginalDec = new import_decimal.default(Number(resolvedSource) || 0).plus(optionSum);
  const mainOriginalStr = mainOriginalDec.toDecimalPlaces(2).toFixed(2);
  let mainSellingDec;
  if (isV2 && metadata.main_product_selling_price != null) {
    mainSellingDec = new import_decimal.default(Number(metadata.main_product_selling_price) || 0);
  } else if (metadata.main_product_selling_price != null && metadata.main_product_original_price != null) {
    const legacyOriginal = new import_decimal.default(Number(metadata.main_product_original_price) || 0);
    const legacySelling = new import_decimal.default(Number(metadata.main_product_selling_price) || 0);
    const legacyDiscount = legacyOriginal.minus(legacySelling);
    mainSellingDec = mainOriginalDec.minus(legacyDiscount);
  } else if (product.original_price != null && product.selling_price != null && new import_decimal.default(Number(product.original_price) || 0).greaterThan(
    new import_decimal.default(Number(product.selling_price) || 0)
  )) {
    const topOriginal = new import_decimal.default(Number(product.original_price) || 0);
    const topSelling = new import_decimal.default(Number(product.selling_price) || 0);
    const legacyDiscount = topOriginal.minus(topSelling);
    mainSellingDec = mainOriginalDec.minus(legacyDiscount);
  } else {
    mainSellingDec = mainOriginalDec;
  }
  const mainSellingStr = mainSellingDec.toDecimalPlaces(2).toFixed(2);
  metadata.source_product_price = resolvedSource;
  metadata.main_product_original_price = mainOriginalStr;
  metadata.main_product_selling_price = mainSellingStr;
  metadata.price_schema_version = 2;
  const composedSellingPrice = (0, import_utils.composeLinePrice)({
    mainPrice: mainSellingStr,
    bundle: normalizedBundle
  });
  const composedOriginalPrice = (0, import_utils.composeLinePrice)({
    mainPrice: mainOriginalStr,
    bundle: normalizedBundle,
    useOriginalBundle: true
  });
  const finalOriginalPrice = (0, import_utils.resolveManualOverrideLineOriginalPrice)(
    { num: product.num, metadata, lineOriginalPrice: product.original_price },
    composedOriginalPrice
  );
  const discountList = (0, import_manualProductDiscount.ensureManualProductDiscountList)({
    discountList: product.discount_list,
    metadata,
    originalPrice: finalOriginalPrice,
    sellingPrice: composedSellingPrice,
    quantity: getSafeProductNum(product.num)
  });
  return {
    order_detail_id: product.order_detail_id || null,
    product_id: product.product_id,
    num: getSafeProductNum(product.num),
    product_variant_id: product.product_variant_id,
    product_option_item: normalizedOptions,
    selling_price: composedSellingPrice,
    original_price: finalOriginalPrice,
    tax_fee: product.tax_fee || "0.00",
    is_charge_tax: product.is_charge_tax ?? 0,
    discount_list: discountList,
    product_bundle: normalizedBundle,
    metadata,
    note: product.note != null ? String(product.note) : ""
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  buildProductLineFingerprint,
  createEmptySummary,
  getSafeProductNum,
  isSkuOnlyDeleteIdentity,
  normalizeOrderProduct
});
