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/VenueBooking/utils/slotMerge.ts
var slotMerge_exports = {};
__export(slotMerge_exports, {
  buildPriceBreakdown: () => buildPriceBreakdown,
  buildVenueBookingEntry: () => buildVenueBookingEntry,
  buildVenueIdentityKey: () => buildVenueIdentityKey,
  buildVenueResourceMetadata: () => buildVenueResourceMetadata,
  expandMergedSlotToIndividual: () => expandMergedSlotToIndividual,
  mergeConsecutiveSlots: () => mergeConsecutiveSlots
});
module.exports = __toCommonJS(slotMerge_exports);
var import_decimal = __toESM(require("decimal.js"));
var import_dayjs = __toESM(require("dayjs"));
var import_utils = require("../../../modules/Order/utils");
function buildVenueIdentityKey(resourceId, groupIndex) {
  return `venue:${resourceId}:${groupIndex}:${(0, import_utils.createUuidV4)()}`;
}
function mergeConsecutiveSlots(slots) {
  if (!slots.length)
    return [];
  const sorted = [...slots].sort((a, b) => a.startTime.localeCompare(b.startTime));
  const groups = [];
  let currentSlots = [sorted[0]];
  let currentStart = sorted[0].startTime;
  let currentEnd = sorted[0].endTime;
  let totalPrice = new import_decimal.default(sorted[0].price || "0");
  for (let i = 1; i < sorted.length; i++) {
    const slot = sorted[i];
    if (slot.startTime === currentEnd) {
      currentEnd = slot.endTime;
      totalPrice = totalPrice.add(new import_decimal.default(slot.price || "0"));
      currentSlots.push(slot);
    } else {
      groups.push({
        startTime: currentStart,
        endTime: currentEnd,
        totalPrice: totalPrice.toFixed(2),
        slotCount: currentSlots.length,
        slots: currentSlots
      });
      currentSlots = [slot];
      currentStart = slot.startTime;
      currentEnd = slot.endTime;
      totalPrice = new import_decimal.default(slot.price || "0");
    }
  }
  groups.push({
    startTime: currentStart,
    endTime: currentEnd,
    totalPrice: totalPrice.toFixed(2),
    slotCount: currentSlots.length,
    slots: currentSlots
  });
  return groups;
}
function buildPriceBreakdown(params) {
  const { group, productId, quotation } = params;
  if (!group.slots.length)
    return [];
  const entries = [];
  for (const slot of group.slots) {
    const unitPrice = Number(slot.price || "0");
    const shelfId = quotation ? quotation.getQuotationShelfId({ productId, datetime: slot.startTime }) : 0;
    const startHm = (0, import_dayjs.default)(slot.startTime, "YYYY-MM-DD HH:mm").format("YYYY-MM-DD HH:mm");
    const endHm = (0, import_dayjs.default)(slot.endTime, "YYYY-MM-DD HH:mm").format("YYYY-MM-DD HH:mm");
    const last = entries[entries.length - 1];
    if (last && last.unit_price === unitPrice && last.quotation_shelf_id === shelfId && last.end_time === startHm) {
      last.end_time = endHm;
      last.quantity += 1;
    } else {
      entries.push({
        start_time: startHm,
        end_time: endHm,
        unit_price: unitPrice,
        quotation_shelf_id: shelfId,
        quantity: 1
      });
    }
  }
  return entries;
}
function buildVenueResourceMetadata(params) {
  const { mapping, rawResource } = params;
  return {
    form_name: (rawResource == null ? void 0 : rawResource.form_name) ?? "",
    resource_name: (rawResource == null ? void 0 : rawResource.main_field) ?? mapping.resourceName ?? "",
    combined_resource: (rawResource == null ? void 0 : rawResource.combined_resource) ?? null
  };
}
function buildVenueBookingEntry(params) {
  const { group, resourceId, mapping, rawResource, bookingUuid, productUid, childResources } = params;
  const startMoment = (0, import_dayjs.default)(group.startTime, "YYYY-MM-DD HH:mm");
  const endMoment = (0, import_dayjs.default)(group.endTime, "YYYY-MM-DD HH:mm");
  const duration = endMoment.diff(startMoment, "minute");
  const resourceEntry = {
    relation_type: "form",
    like_status: "common",
    id: resourceId,
    main_field: mapping.resourceName,
    form_id: (rawResource == null ? void 0 : rawResource.form_id) ?? mapping.formId,
    relation_id: resourceId,
    capacity: 1,
    metadata: {}
  };
  if (childResources && childResources.length) {
    resourceEntry.children = childResources.map((child) => ({
      relation_type: "form",
      like_status: "common",
      id: child.resourceId,
      main_field: child.main_field || "",
      form_id: child.form_id ?? child.formId,
      relation_id: child.resourceId,
      capacity: child.capacity ?? 1,
      metadata: {}
    }));
  }
  return {
    schedule_event_id: null,
    appointment_status: "new",
    start_date: startMoment.format("YYYY-MM-DD"),
    start_time: startMoment.format("HH:mm"),
    end_date: endMoment.format("YYYY-MM-DD"),
    end_time: endMoment.format("HH:mm"),
    select_date: startMoment.format("YYYY-MM-DD"),
    duration,
    sub_type: "minutes",
    like_status: "common",
    number: 1,
    is_all: false,
    schedule_id: 0,
    product_uid: productUid,
    resources: [resourceEntry],
    relation_products: [],
    relation_forms: [],
    holder: null,
    metadata: {
      unique_identification_number: bookingUuid,
      venue_booking: true,
      resource_id: resourceId,
      product_id: mapping.productId
    }
  };
}
function expandMergedSlotToIndividual(product, slotDurationMinutes) {
  const meta = product.metadata || {};
  const resourceId = meta.resource_id;
  if (resourceId == null)
    return [];
  const startTime = meta.start_time;
  const endTime = meta.end_time;
  if (!startTime || !endTime)
    return [];
  const productId = Number(product.product_id);
  const breakdown = meta.price_breakdown;
  const result = [];
  let cursor = (0, import_dayjs.default)(startTime, "YYYY-MM-DD HH:mm");
  const end = (0, import_dayjs.default)(endTime, "YYYY-MM-DD HH:mm");
  if (breakdown == null ? void 0 : breakdown.length) {
    const priceMap = /* @__PURE__ */ new Map();
    for (const entry of breakdown) {
      let entryCursor = (0, import_dayjs.default)(entry.start_time, "YYYY-MM-DD HH:mm");
      const entryEnd = (0, import_dayjs.default)(entry.end_time, "YYYY-MM-DD HH:mm");
      while (entryCursor.isBefore(entryEnd)) {
        priceMap.set(entryCursor.format("HH:mm"), entry.unit_price);
        entryCursor = entryCursor.add(slotDurationMinutes, "minute");
      }
    }
    while (cursor.isBefore(end)) {
      const slotEnd = cursor.add(slotDurationMinutes, "minute");
      const hm = cursor.format("HH:mm");
      const price = priceMap.get(hm) ?? 0;
      result.push({
        resourceId,
        productId,
        startTime: cursor.format("YYYY-MM-DD HH:mm"),
        endTime: slotEnd.format("YYYY-MM-DD HH:mm"),
        price: new import_decimal.default(price).toFixed(2)
      });
      cursor = slotEnd;
    }
  } else {
    const slotCount = meta.slot_count || 1;
    const totalPrice = new import_decimal.default(product.selling_price || "0");
    const perSlotPrice = slotCount > 0 ? totalPrice.div(slotCount).toFixed(2) : totalPrice.toFixed(2);
    while (cursor.isBefore(end)) {
      const slotEnd = cursor.add(slotDurationMinutes, "minute");
      result.push({
        resourceId,
        productId,
        startTime: cursor.format("YYYY-MM-DD HH:mm"),
        endTime: slotEnd.format("YYYY-MM-DD HH:mm"),
        price: perSlotPrice
      });
      cursor = slotEnd;
    }
  }
  return result;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  buildPriceBreakdown,
  buildVenueBookingEntry,
  buildVenueIdentityKey,
  buildVenueResourceMetadata,
  expandMergedSlotToIndividual,
  mergeConsecutiveSlots
});
