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/quotationPrice.ts
var quotationPrice_exports = {};
__export(quotationPrice_exports, {
  calculateBaseSalesProductBookingPrice: () => calculateBaseSalesProductBookingPrice
});
module.exports = __toCommonJS(quotationPrice_exports);
var import_dayjs = __toESM(require("dayjs"));
var import_decimal = __toESM(require("decimal.js"));
function toFiniteNumber(value, fallback = 0) {
  const parsedValue = Number(value);
  if (!Number.isFinite(parsedValue))
    return fallback;
  return parsedValue;
}
function toPositiveInt(value, fallback = 1) {
  const parsedValue = Math.floor(Number(value));
  if (!Number.isFinite(parsedValue) || parsedValue < 1)
    return fallback;
  return parsedValue;
}
function toPriceString(value) {
  return new import_decimal.default(Number(value) || 0).toDecimalPlaces(2).toFixed(2);
}
function normalizeDateTime(value) {
  if (typeof value !== "string" || !value.trim())
    return null;
  const normalized = value.includes(":") ? value : `${value} 00:00:00`;
  const datetime = (0, import_dayjs.default)(normalized);
  if (!datetime.isValid())
    return null;
  return datetime;
}
function buildBookingDateTime(date, time) {
  if (typeof date !== "string" || !date.trim())
    return null;
  const timeText = typeof time === "string" && time.trim() ? time.trim() : "00:00";
  const datetime = (0, import_dayjs.default)(`${date.trim()} ${timeText}`);
  if (!datetime.isValid())
    return null;
  return datetime;
}
function getDurationUnit(type) {
  const normalizedType = String(type || "").toLowerCase();
  if (normalizedType === "day" || normalizedType === "days")
    return "day";
  if (normalizedType === "minute" || normalizedType === "minutes")
    return "minute";
  return null;
}
function getProductId(product) {
  const productId = toFiniteNumber(product.product_id ?? product.id, NaN);
  if (!Number.isFinite(productId))
    return null;
  return productId;
}
function getProductVariantId(product) {
  const variantId = toFiniteNumber(
    product.product_variant_id ?? product.variant_id,
    0
  );
  if (!Number.isFinite(variantId) || variantId <= 0)
    return void 0;
  return variantId;
}
function getFallbackPrice(params) {
  const product = params.product || {};
  return toPriceString(
    params.fallback_price ?? product.price ?? product.selling_price ?? product.original_price ?? 0
  );
}
function getProductQuantity(product) {
  return toPositiveInt(product.num ?? product.quantity, 1);
}
function getBundleProductId(bundle) {
  const productId = toFiniteNumber(
    bundle.bundle_product_id ?? bundle._bundle_product_id,
    NaN
  );
  if (!Number.isFinite(productId))
    return null;
  return productId;
}
function getBundleVariantId(bundle) {
  const variantId = toFiniteNumber(
    bundle.bundle_variant_id ?? bundle.variant_id,
    0
  );
  if (!Number.isFinite(variantId) || variantId <= 0)
    return void 0;
  return variantId;
}
function getBundleFallbackPrice(bundle) {
  return toPriceString(
    bundle.bundle_selling_price ?? bundle.price ?? bundle.original_price ?? bundle.base_price ?? 0
  );
}
function shouldSplitByDuration(duration, start, end) {
  if (!duration)
    return false;
  if (!start || !end || !end.isAfter(start))
    return false;
  const unit = getDurationUnit(duration.type);
  const value = toFiniteNumber(duration.value);
  return !!unit && value > 0;
}
function buildTimeSegments(params) {
  const booking = params.booking || {};
  const explicitDatetime = normalizeDateTime(params.datetime);
  const bookingStart = buildBookingDateTime(booking.start_date, booking.start_time);
  const start = bookingStart || explicitDatetime || (0, import_dayjs.default)();
  const bookingEnd = buildBookingDateTime(booking.end_date, booking.end_time);
  if (!shouldSplitByDuration(params.duration, start, bookingEnd)) {
    return [{ start }];
  }
  const unit = getDurationUnit(params.duration.type);
  const value = toFiniteNumber(params.duration.value);
  const segments = [];
  let cursor = start;
  let guard = 0;
  while (cursor.isBefore(bookingEnd) && guard < 1e4) {
    const next = cursor.add(value, unit);
    segments.push({
      start: cursor,
      end: next.isBefore(bookingEnd) ? next : bookingEnd ?? void 0
    });
    cursor = next;
    guard += 1;
  }
  return segments.length ? segments : [{ start }];
}
function formatTimePoint(datetime) {
  return datetime.format("YYYY-MM-DD HH:mm:ss");
}
function buildPriceSegment(params) {
  const timePoint = formatTimePoint(params.segment.start);
  const quotedPrice = params.quotation && params.productId !== null ? params.quotation.getPriceForProduct({
    productId: params.productId,
    variantId: params.variantId,
    datetime: timePoint,
    customer_id: params.customerId
  }) : null;
  const unitPrice = toPriceString(quotedPrice ?? params.fallbackPrice);
  const quotationShelfId = quotedPrice !== null && params.quotation && params.productId !== null ? params.quotation.getQuotationShelfId({
    productId: params.productId,
    variantId: params.variantId,
    datetime: timePoint,
    customer_id: params.customerId
  }) : 0;
  return {
    start_datetime: timePoint,
    end_datetime: params.segment.end ? formatTimePoint(params.segment.end) : void 0,
    time_point: timePoint,
    unit_price: unitPrice,
    quantity: 1,
    total_price: unitPrice,
    quotation_shelf_id: quotationShelfId,
    source: quotedPrice !== null ? "quotation" : "fallback"
  };
}
function calculatePriceForProduct(params) {
  var _a;
  const segments = params.segments.map((segment) => buildPriceSegment({
    quotation: params.quotation,
    productId: params.productId,
    variantId: params.variantId,
    customerId: params.customerId,
    fallbackPrice: params.fallbackPrice,
    segment
  }));
  const unitPrice = segments.reduce(
    (total, segment) => total.plus(segment.total_price),
    new import_decimal.default(0)
  );
  const totalPrice = unitPrice.times(params.quantity);
  const quotationShelfId = ((_a = segments.find((segment) => segment.quotation_shelf_id)) == null ? void 0 : _a.quotation_shelf_id) || 0;
  return {
    unitPrice,
    totalPrice,
    quotationShelfId,
    segments
  };
}
function calculateBundlePrices(params, segments) {
  var _a;
  const bundleList = ((_a = params.product) == null ? void 0 : _a.product_bundle) || [];
  if (!bundleList.length)
    return void 0;
  return bundleList.map((bundle) => {
    const productId = getBundleProductId(bundle);
    const variantId = getBundleVariantId(bundle);
    const quantity = getProductQuantity(bundle);
    const price = calculatePriceForProduct({
      quotation: params.quotation,
      productId,
      variantId,
      customerId: params.customer_id,
      quantity,
      fallbackPrice: getBundleFallbackPrice(bundle),
      segments
    });
    return {
      bundle_id: bundle.bundle_id ?? bundle.id,
      group_id: bundle.group_id,
      bundle_group_id: bundle.bundle_group_id,
      bundle_product_id: productId,
      bundle_variant_id: variantId ?? 0,
      unit_price: price.unitPrice.toDecimalPlaces(2).toFixed(2),
      total_price: price.totalPrice.toDecimalPlaces(2).toFixed(2),
      quantity,
      quotation_shelf_id: price.quotationShelfId,
      source: price.segments.some((segment) => segment.source === "quotation") ? "quotation" : "fallback",
      segments: price.segments
    };
  });
}
function calculateBaseSalesProductBookingPrice(params) {
  const product = params.product || {};
  const productId = getProductId(product);
  const variantId = getProductVariantId(product);
  const productQuantity = getProductQuantity(product);
  const fallbackPrice = getFallbackPrice(params);
  const timeSegments = buildTimeSegments(params);
  const price = calculatePriceForProduct({
    quotation: params.quotation,
    productId,
    variantId,
    customerId: params.customer_id,
    quantity: productQuantity,
    fallbackPrice,
    segments: timeSegments
  });
  const bundlePrices = calculateBundlePrices(params, timeSegments);
  return {
    product_id: productId,
    product_variant_id: variantId ?? 0,
    customer_id: params.customer_id,
    unit_price: price.unitPrice.toDecimalPlaces(2).toFixed(2),
    total_price: price.totalPrice.toDecimalPlaces(2).toFixed(2),
    quantity: productQuantity,
    duration: params.duration,
    quotation_shelf_id: price.quotationShelfId,
    segments: price.segments,
    ...bundlePrices ? { product_bundle: bundlePrices } : {}
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  calculateBaseSalesProductBookingPrice
});
