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/BookingTicket/utils/addProductDecision.ts
var addProductDecision_exports = {};
__export(addProductDecision_exports, {
  buildCacheItemFromCartDetail: () => buildCacheItemFromCartDetail,
  buildCacheItemFromDetail: () => buildCacheItemFromDetail,
  buildRequiresDetailPayload: () => buildRequiresDetailPayload,
  decideAddProduct: () => decideAddProduct,
  decideAfterDetail: () => decideAfterDetail,
  decideAutoClose: () => decideAutoClose,
  getIsEject: () => getIsEject,
  getIsOnlySession: () => getIsOnlySession,
  prepareBookingCacheItem: () => prepareBookingCacheItem,
  transformDetailToProductAndBooking: () => transformDetailToProductAndBooking
});
module.exports = __toCommonJS(addProductDecision_exports);
var import_dayjs = __toESM(require("dayjs"));
var import_BookingContext = require("../../../modules/BookingContext");
var import_transformBaseProductToOrderProduct = require("../../BaseSales/utils/transformBaseProductToOrderProduct");
function needsSpecDetailModal(item) {
  if (item == null ? void 0 : item.open_sold_weight)
    return true;
  if (item == null ? void 0 : item.isOpenDetailModal)
    return true;
  if (!(item == null ? void 0 : item.cartDetailValue))
    return true;
  return false;
}
function needsBookingEdit(cacheItem, ctx) {
  if (isNormalBookingProduct(cacheItem))
    return false;
  const isAutoAllocationOn = (ctx == null ? void 0 : ctx.isAutoAllocationOn) || (() => true);
  return !(0, import_BookingContext.getIsAutoClose)(cacheItem, isAutoAllocationOn);
}
function buildRequiresBookingEditPayload(cacheItem, ctx) {
  return {
    cacheItem,
    customerId: ctx == null ? void 0 : ctx.customerId,
    date: typeof (ctx == null ? void 0 : ctx.date) === "string" ? ctx.date : null
  };
}
function decideAddProduct(item, ctx) {
  const derivedCtx = withDerivedBookingCtx(ctx);
  if (needsSpecDetailModal(item)) {
    return {
      action: "requiresDetail",
      payload: buildRequiresDetailPayload(item, derivedCtx)
    };
  }
  const cacheItem = prepareBookingCacheItem(
    buildCacheItemFromCartDetail(item, derivedCtx),
    derivedCtx
  );
  if (needsBookingEdit(cacheItem, derivedCtx)) {
    return {
      action: "requiresBookingEdit",
      cacheItem,
      payload: buildRequiresBookingEditPayload(cacheItem, derivedCtx)
    };
  }
  return { action: "add", cacheItem };
}
function decideAfterDetail(cacheItem, ctx) {
  const derivedCtx = withDerivedBookingCtx(ctx);
  const extended = prepareBookingCacheItem(cacheItem, derivedCtx);
  if (needsBookingEdit(extended, derivedCtx)) {
    return {
      action: "requiresBookingEdit",
      cacheItem: extended,
      payload: buildRequiresBookingEditPayload(extended, derivedCtx)
    };
  }
  return { action: "add", cacheItem: extended };
}
function isNormalBookingProduct(item) {
  return !(0, import_BookingContext.isBookingProduct)(item);
}
function hasPreparedBookingExtend(cacheItem) {
  var _a;
  if ((0, import_BookingContext.productNeedsResourceExtend)(cacheItem) && !(0, import_BookingContext.hasActualResourceSelection)(cacheItem)) {
    return false;
  }
  const ext = (cacheItem == null ? void 0 : cacheItem._extend) || {};
  const hasResourceState = Boolean(
    (0, import_BookingContext.hasActualResourceSelection)(cacheItem) && ext.capacity && (ext.endDate || ext.end_date)
  );
  const hasSessionState = Boolean(
    (0, import_BookingContext.isSessionProduct)(cacheItem) && ((_a = ext.other) == null ? void 0 : _a.session) && ext.start_time && (ext.end_time || ext.endDate)
  );
  const hasMultiDayState = Boolean(isNormalBookingProduct(cacheItem) === false && isMultiDayLike(cacheItem));
  const hasExplicitTimeState = Boolean(
    ext.duration && (ext.start_date || ext.startDate) && ext.start_time && (ext.end_date && ext.end_time || ext.endDate)
  );
  return hasResourceState || hasSessionState || hasMultiDayState || hasExplicitTimeState;
}
function formatBookingDateForUI(date) {
  if (date == null || date === "")
    return null;
  const parsed = (0, import_dayjs.default)(date);
  return parsed.isValid() ? parsed.format("YYYY-MM-DD") : null;
}
function withDerivedBookingCtx(ctx) {
  if (!ctx)
    return {};
  return {
    ...ctx,
    presetStartTime: ctx.presetStartTime ?? (0, import_BookingContext.derivePresetStartTimeFromDate)(ctx.date)
  };
}
function isMultiDayLike(cacheItem) {
  var _a;
  const ext = (cacheItem == null ? void 0 : cacheItem._extend) || {};
  return Boolean(
    ((_a = cacheItem == null ? void 0 : cacheItem.duration) == null ? void 0 : _a.type) === "days" && ext.duration && ext.start_date && ext.end_date
  );
}
function prepareBookingCacheItem(cacheItem, ctx) {
  if (isNormalBookingProduct(cacheItem) || hasPreparedBookingExtend(cacheItem)) {
    return cacheItem;
  }
  return (0, import_BookingContext.getProductExtend)({
    cacheItem,
    ctx: withDerivedBookingCtx(ctx),
    isDisabledTime: true
  });
}
function decideAutoClose(item, ctx) {
  const decision = decideAddProduct(item, ctx);
  if (decision.action === "add") {
    return { autoClose: true, cacheItem: decision.cacheItem };
  }
  if (decision.action === "requiresBookingEdit") {
    return { autoClose: false, cacheItem: decision.cacheItem };
  }
  return { autoClose: false };
}
function getIsEject(item, type = "select") {
  const isSession = (0, import_BookingContext.isSessionProduct)(item);
  const isSoldByWeight = Boolean(item == null ? void 0 : item.open_sold_weight);
  const need = type === "detail" || ((item == null ? void 0 : item.bundle_group_count) || 0) > 0 || ((item == null ? void 0 : item.option_group_count) || 0) > 0 || ((item == null ? void 0 : item.is_variant) || 0) > 0 || isSession || isSoldByWeight;
  return need ? 1 : 0;
}
function getIsOnlySession(item) {
  const isSession = (0, import_BookingContext.isSessionProduct)(item);
  return !(((item == null ? void 0 : item.bundle_group_count) || 0) > 0 || ((item == null ? void 0 : item.option_group_count) || 0) > 0 || ((item == null ? void 0 : item.is_variant) || 0) > 0) && isSession;
}
function buildRequiresDetailPayload(item, ctx) {
  const isOnlySession = getIsOnlySession(item);
  const isEject = getIsEject(item, (ctx == null ? void 0 : ctx.type) || "select");
  return {
    item,
    showConfig: {
      option: ((item == null ? void 0 : item.option_group_count) || 0) > 0,
      session: (0, import_BookingContext.isSessionProduct)(item),
      variant: ((item == null ? void 0 : item.is_variant) || 0) > 0,
      package: ((item == null ? void 0 : item.bundle_group_count) || 0) > 0,
      number: Boolean(item == null ? void 0 : item.open_sold_weight)
    },
    isOnlySession,
    isEject: isEject ? 1 : 0,
    customerId: ctx == null ? void 0 : ctx.customerId,
    date: formatBookingDateForUI(ctx == null ? void 0 : ctx.date),
    productData: item
  };
}
function buildCacheItemFromCartDetail(item, ctx) {
  var _a;
  const cartDetailValue = item.cartDetailValue || {};
  const other = JSON.parse(JSON.stringify(cartDetailValue || {}));
  other.session = cartDetailValue.session;
  const resolvedId = item.id ?? item.product_id;
  let extend = (0, import_BookingContext.applySessionTimesToExtend)(
    item,
    {
      start_date: (ctx == null ? void 0 : ctx.date) || void 0,
      /** 列表连点 / 防抖合并时以 ctx.quantity 为准，避免 cartDetailValue 默认 1 盖掉合并数量 */
      quantity: (ctx == null ? void 0 : ctx.quantity) ?? (cartDetailValue == null ? void 0 : cartDetailValue.quantity) ?? 1,
      product_name: item.title,
      other,
      isNormalProduct: !(0, import_BookingContext.isBookingProduct)(item),
      price: ((_a = item == null ? void 0 : item._extend) == null ? void 0 : _a.price) ?? (item == null ? void 0 : item.price)
    },
    { date: ctx == null ? void 0 : ctx.date }
  );
  return {
    ...item,
    id: resolvedId,
    product_id: resolvedId,
    _key: cartDetailValue.key,
    _extend: extend,
    new: 1
  };
}
function buildCacheItemFromDetail(item, detailResult, ctx) {
  var _a, _b, _c;
  const _currentItem = detailResult.detail || item;
  const _detail = _currentItem;
  const detailExtend = (_detail == null ? void 0 : _detail._extend) || {};
  const other = JSON.parse(JSON.stringify(detailResult.e || {}));
  other.session = (_a = detailResult.e) == null ? void 0 : _a.session;
  const resolvedId = _currentItem.id ?? _currentItem.product_id;
  const mergedItem = { ...item, ..._detail, extension_type: _detail.extension_type ?? item.extension_type };
  const runtimeExtend = (0, import_BookingContext.applySessionTimesToExtend)(
    mergedItem,
    {
      start_date: (ctx == null ? void 0 : ctx.date) || detailExtend.start_date || void 0,
      quantity: (ctx == null ? void 0 : ctx.quantity) ?? ((_b = detailResult.e) == null ? void 0 : _b.quantity) ?? detailExtend.quantity ?? 1,
      price: detailExtend.price ?? (_detail == null ? void 0 : _detail.price) ?? (item == null ? void 0 : item.price),
      product_name: _currentItem.title ?? detailExtend.product_name,
      other,
      isNormalProduct: !(0, import_BookingContext.isBookingProduct)(mergedItem)
    },
    { date: ctx == null ? void 0 : ctx.date }
  );
  const extend = {
    ...detailExtend,
    ...runtimeExtend,
    other
  };
  const note = detailExtend.note ?? (_detail == null ? void 0 : _detail.note);
  return {
    ..._detail,
    id: resolvedId,
    product_id: resolvedId,
    extension_type: mergedItem.extension_type,
    _key: (_c = detailResult.e) == null ? void 0 : _c.key,
    ...note != null && note !== "" ? { note: String(note) } : {},
    _extend: extend,
    new: 1
  };
}
function transformDetailToProductAndBooking(cacheItem, ctx) {
  const preparedCacheItem = prepareBookingCacheItem(cacheItem, withDerivedBookingCtx(ctx));
  const payload = buildBasePayloadFromCacheItem(preparedCacheItem, ctx);
  const productInput = (0, import_transformBaseProductToOrderProduct.transformBaseProductToOrderProduct)({
    payload,
    sourceProduct: preparedCacheItem
  });
  if (!productInput) {
    throw new Error(
      "[BookingTicket] transformDetailToProductAndBooking: product transform failed (missing numeric item.id / item.product_id)"
    );
  }
  const isNormalProduct = isNormalBookingProduct(preparedCacheItem);
  let booking;
  if (!isNormalProduct) {
    booking = (0, import_BookingContext.cacheItemToBookingInput)(preparedCacheItem, { bookingConfig: ctx == null ? void 0 : ctx.bookingConfig });
  }
  return { product: productInput, booking, cacheItem: preparedCacheItem };
}
function buildBasePayloadFromCacheItem(cacheItem, ctx) {
  var _a, _b, _c, _d;
  const other = ((_a = cacheItem == null ? void 0 : cacheItem._extend) == null ? void 0 : _a.other) || {};
  const quantity = (ctx == null ? void 0 : ctx.quantity) != null && ctx.quantity > 0 ? ctx.quantity : ((_b = cacheItem == null ? void 0 : cacheItem._extend) == null ? void 0 : _b.quantity) ?? 1;
  const resolvedPid = (cacheItem == null ? void 0 : cacheItem.product_id) ?? (cacheItem == null ? void 0 : cacheItem.id);
  const extend = (cacheItem == null ? void 0 : cacheItem._extend) || {};
  return {
    id: (cacheItem == null ? void 0 : cacheItem.id) ?? (cacheItem == null ? void 0 : cacheItem.product_id),
    product_id: resolvedPid,
    variant_id: (other == null ? void 0 : other.product_variant_id) ?? (other == null ? void 0 : other.variant_id) ?? 0,
    quantity,
    option: (other == null ? void 0 : other.option) || [],
    bundle: (other == null ? void 0 : other.bundle) || ((_c = extend == null ? void 0 : extend.skuValue) == null ? void 0 : _c.bundle) || ((_d = extend == null ? void 0 : extend._skuValue) == null ? void 0 : _d.bundle) || [],
    unique: other == null ? void 0 : other.unique,
    session: other == null ? void 0 : other.session,
    note: extend == null ? void 0 : extend.note,
    price: (extend == null ? void 0 : extend.price) ?? (cacheItem == null ? void 0 : cacheItem.price),
    selling_price: (extend == null ? void 0 : extend.price) ?? (cacheItem == null ? void 0 : cacheItem.price),
    line_total: extend == null ? void 0 : extend.total,
    total: extend == null ? void 0 : extend.total,
    origin_total: extend == null ? void 0 : extend.origin_total,
    price_override: extend == null ? void 0 : extend.priceOverride,
    bundle_edit: extend == null ? void 0 : extend.bundle_edit,
    discount_reason: extend == null ? void 0 : extend.discount_reason,
    discount_list: cacheItem == null ? void 0 : cacheItem.discount_list,
    _extend: extend
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  buildCacheItemFromCartDetail,
  buildCacheItemFromDetail,
  buildRequiresDetailPayload,
  decideAddProduct,
  decideAfterDetail,
  decideAutoClose,
  getIsEject,
  getIsOnlySession,
  prepareBookingCacheItem,
  transformDetailToProductAndBooking
});
