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/BookingContext/utils/productExtend.ts
var productExtend_exports = {};
__export(productExtend_exports, {
  derivePresetStartTimeFromDate: () => derivePresetStartTimeFromDate,
  getIsAutoClose: () => getIsAutoClose,
  getProductExtend: () => getProductExtend,
  getServiceStartTimeAndEndTime: () => getServiceStartTimeAndEndTime,
  getSumCapacity: () => import_resources.getSumCapacity,
  getTimeObj: () => getTimeObj
});
module.exports = __toCommonJS(productExtend_exports);
var import_dayjs = __toESM(require("dayjs"));
var import_resources = require("./resources");
var import_resourceSelection = require("./resourceSelection");
var import_serviceTimes = require("./serviceTimes");
var import_timeSlices = require("./timeSlices");
var import_flexible = require("./flexible");
function derivePresetStartTimeFromDate(date) {
  if (date == null)
    return void 0;
  const d = (0, import_dayjs.default)(date);
  if (!d.isValid())
    return void 0;
  const hhmm = d.format("HH:mm");
  if (hhmm === "00:00")
    return void 0;
  return hhmm;
}
function getAppointmentTimingPreference(ctx) {
  var _a, _b, _c;
  return ((_c = (_b = (_a = ctx == null ? void 0 : ctx.bookingConfig) == null ? void 0 : _a.config) == null ? void 0 : _b.information_tab) == null ? void 0 : _c.appointment_timing_preference) || "sequential";
}
function getFlexibleOption(params) {
  var _a, _b, _c, _d, _e;
  const { cacheItem, useStartTime } = params;
  const duration = (0, import_flexible.getDurationValue)(cacheItem == null ? void 0 : cacheItem.duration);
  if (duration !== "flexible")
    return null;
  const startDate = (0, import_dayjs.default)(
    `${(0, import_dayjs.default)((_a = cacheItem == null ? void 0 : cacheItem._extend) == null ? void 0 : _a.start_date).format("YYYY-MM-DD")} ${useStartTime || ((_b = cacheItem == null ? void 0 : cacheItem._extend) == null ? void 0 : _b.start_time) || "00:00"}`
  );
  const usable = (0, import_resources.getUsableTime)(cacheItem);
  const usableEndAt = ((_d = (_c = usable == null ? void 0 : usable._extend) == null ? void 0 : _c.usableTime) == null ? void 0 : _d.end_at) ? (0, import_dayjs.default)(usable._extend.usableTime.end_at) : null;
  const endDate = (0, import_timeSlices.getEndDate)(
    startDate,
    "flexible",
    usableEndAt,
    (_e = params.ctx) == null ? void 0 : _e.shopOpeningHours
  );
  const timeValue = endDate.diff(startDate, "minute");
  return { label: String(timeValue), value: import_flexible.flexibleObj.create(timeValue) };
}
function getTimeObj(params) {
  var _a, _b, _c;
  const { cacheItem, useStartTime, useDuration, ctx } = params;
  const isMultiDay = (0, import_serviceTimes.isMultiDayProduct)(cacheItem);
  const flexibleOption = getFlexibleOption({ cacheItem, useStartTime, ctx });
  const baseSlices = (0, import_timeSlices.sliceDayIntoFiveMinutes)(
    (_c = (_b = (_a = ctx == null ? void 0 : ctx.bookingConfig) == null ? void 0 : _a.config) == null ? void 0 : _b.basic) == null ? void 0 : _c.service_time,
    isMultiDay
  );
  const timeSlices = [...baseSlices.timeSlices];
  const durationSlicesBasedOnTime = [...baseSlices.durationSlicesBasedOnTime];
  if (flexibleOption) {
    durationSlicesBasedOnTime.unshift(flexibleOption);
  }
  if (useDuration && !durationSlicesBasedOnTime.some((d) => d.value === useDuration)) {
    durationSlicesBasedOnTime.unshift({
      label: String(useDuration),
      value: useDuration
    });
  }
  return { timeSlices, durationSlicesBasedOnTime };
}
function getServiceStartTimeAndEndTime(params) {
  var _a, _b, _c, _d, _e;
  const { cacheItem, timeObj, ctx } = params;
  if (cacheItem == null ? void 0 : cacheItem.isCustomItem) {
    return { duration: null };
  }
  const appointmentTimingPreference = getAppointmentTimingPreference(ctx);
  const lastServer = ctx.previousService || null;
  const resolveDuration = () => {
    var _a2;
    if ((0, import_serviceTimes.isMultiDayProduct)(cacheItem))
      return (0, import_serviceTimes.getDays)(cacheItem, "days");
    return (0, import_timeSlices.findNextDuration)(cacheItem.duration, timeObj.durationSlicesBasedOnTime, (_a2 = cacheItem == null ? void 0 : cacheItem.duration) == null ? void 0 : _a2.value);
  };
  let _extend = { duration: resolveDuration() };
  if (lastServer) {
    const lastStart = (_a = lastServer._extend) == null ? void 0 : _a.startDate;
    const lastEnd = (_b = lastServer._extend) == null ? void 0 : _b.endDate;
    if (appointmentTimingPreference === "parallel") {
      _extend.start_time = (0, import_dayjs.default)(lastStart).format("HH:mm");
    } else if ((0, import_dayjs.default)(lastEnd).isAfter((0, import_dayjs.default)(lastStart), "day")) {
      _extend.start_time = (_c = timeObj.timeSlices[timeObj.timeSlices.length - 1]) == null ? void 0 : _c.value;
    } else {
      _extend.start_time = lastEnd ? (0, import_dayjs.default)(lastEnd).format("HH:mm") : (0, import_dayjs.default)().format("HH:mm");
    }
  } else {
    const presetStartTime = ctx.presetStartTime;
    if (presetStartTime && presetStartTime !== "00:00") {
      _extend.start_time = presetStartTime;
    } else if (cacheItem.currentDefaultTime) {
      _extend.start_time = cacheItem.currentDefaultTime;
    } else {
      _extend.start_time = (0, import_dayjs.default)().format("HH:mm");
    }
  }
  _extend = { ..._extend, ...cacheItem._extend };
  const { startDate, endDate } = (0, import_serviceTimes.getServiceTimes)({ ...cacheItem, _extend });
  _extend.startDate = startDate;
  _extend.endDate = endDate;
  if ((0, import_serviceTimes.isMultiDayProduct)(cacheItem)) {
    _extend.start_time = _extend.start_time || startDate.format("HH:mm");
    _extend.end_time = _extend.end_time || endDate.format("HH:mm");
    _extend.start_date = _extend.start_date ?? startDate;
    _extend.end_date = _extend.end_date ?? endDate;
  }
  const session = (_e = (_d = cacheItem == null ? void 0 : cacheItem._extend) == null ? void 0 : _d.other) == null ? void 0 : _e.session;
  if ((0, import_serviceTimes.isSessionProduct)(cacheItem) && session) {
    const baseDate = ctx.date ? (0, import_dayjs.default)(ctx.date) : (0, import_dayjs.default)();
    const startAt = (0, import_dayjs.default)(`${baseDate.format("YYYY-MM-DD")} ${(0, import_dayjs.default)(session.start_at).format("HH:mm:ss")}`);
    const endAt = (0, import_dayjs.default)(`${baseDate.format("YYYY-MM-DD")} ${(0, import_dayjs.default)(session.end_at).format("HH:mm:ss")}`);
    _extend.start_date = startAt;
    _extend.startDate = startAt;
    _extend.start_time = session.start_time;
    _extend.end_date = endAt;
    _extend.endDate = endAt;
    _extend.end_time = session.end_time;
    _extend.duration = (0, import_serviceTimes.getDays)({ _extend }, "minutes");
  }
  return _extend;
}
function getProductExtend(params) {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
  const { cacheItem, ctx, isDisabledTime } = params;
  const isNew = cacheItem.new || !((_a = cacheItem._extend) == null ? void 0 : _a.endDate);
  const _cacheItem = { ...cacheItem };
  const resourcesOriginMap = ctx.resourcesOriginMap || {};
  _cacheItem._data = {};
  if ((0, import_serviceTimes.isMultiDayProduct)(cacheItem)) {
    _cacheItem._extend = _cacheItem._extend || {};
    _cacheItem._extend.holder_id = ((_b = cacheItem == null ? void 0 : cacheItem._extend) == null ? void 0 : _b.holder_id) || [];
    _cacheItem._extend.sub_type = "days";
  }
  if (isNew) {
    _cacheItem._data.timeObj = getTimeObj({ cacheItem, ctx });
    _cacheItem._extend = getServiceStartTimeAndEndTime({
      cacheItem,
      timeObj: _cacheItem._data.timeObj,
      ctx
    });
    _cacheItem._data.capacitys = cacheItem.capacity;
    _cacheItem._data.resourcesOrigin = (0, import_resources.getResourceByIds)(resourcesOriginMap, cacheItem, {
      resourceTab: (_d = (_c = ctx == null ? void 0 : ctx.bookingConfig) == null ? void 0 : _c.config) == null ? void 0 : _d.resource_tab,
      resourcesOrigin: ctx.resourcesOrigin || []
    });
    _cacheItem._extend.capacity = (0, import_resources.setDefaultCapacitys)({
      capacitys: _cacheItem._data.capacitys,
      cacheItem: _cacheItem
    });
    const { list, maps } = (0, import_resources.formatResources)({
      cacheItem: _cacheItem,
      resourcesOrigin: _cacheItem._data.resourcesOrigin
    });
    _cacheItem._data.resources = list;
    _cacheItem._data.resourceMaps = maps;
    _cacheItem._extend.resource = (0, import_resources.setDefaultResource)({
      cacheItem: _cacheItem,
      resources: _cacheItem._data.resources,
      resourceIdFromCalendar: ctx.resourceIdFromCalendar,
      isAutoAllocationOn: ctx.isAutoAllocationOn
    });
    if ((0, import_flexible.isProductFlexibleDuration)(_cacheItem == null ? void 0 : _cacheItem.duration)) {
      _cacheItem._data.timeObj = getTimeObj({
        cacheItem: _cacheItem,
        useStartTime: _cacheItem._extend.start_time,
        ctx
      });
      _cacheItem._extend.duration = (_g = (_f = (_e = _cacheItem._data.timeObj) == null ? void 0 : _e.durationSlicesBasedOnTime) == null ? void 0 : _f[0]) == null ? void 0 : _g.value;
      const { endDate } = (0, import_serviceTimes.getServiceTimes)(_cacheItem);
      _cacheItem._extend.endDate = endDate;
    }
    _cacheItem.autoClose = getIsAutoClose(_cacheItem, ctx.isAutoAllocationOn || (() => true));
    if (_cacheItem._extend.bundle_edit !== void 0) {
      _cacheItem._extend.bundle_edit = 1;
    }
    if (!isDisabledTime) {
      _cacheItem._time = (/* @__PURE__ */ new Date()).getTime();
    }
  } else {
    if (!_cacheItem._data.capacitys) {
      _cacheItem._data.capacitys = cacheItem.capacity;
    }
    if (!_cacheItem._data.resourcesOrigin) {
      const extraResources = [];
      if (Array.isArray((_h = _cacheItem._extend) == null ? void 0 : _h.event_resources)) {
        _cacheItem._extend.event_resources.forEach((er) => {
          extraResources.push({ form_id: er.form_id, id: er.relation_id });
        });
      }
      _cacheItem._data.resourcesOrigin = (0, import_resources.getResourceByIds)(resourcesOriginMap, cacheItem, {
        extraResources,
        resourceTab: (_j = (_i = ctx == null ? void 0 : ctx.bookingConfig) == null ? void 0 : _i.config) == null ? void 0 : _j.resource_tab,
        resourcesOrigin: ctx.resourcesOrigin || []
      });
    }
    if (!_cacheItem._data.resources) {
      const { list, maps } = (0, import_resources.formatResources)({
        cacheItem: _cacheItem,
        resourcesOrigin: _cacheItem._data.resourcesOrigin
      });
      _cacheItem._data.resources = list;
      _cacheItem._data.resourceMaps = maps;
    }
    _cacheItem._data.timeObj = getTimeObj({
      cacheItem: _cacheItem,
      useStartTime: (_k = _cacheItem._extend) == null ? void 0 : _k.start_time,
      ctx
    });
  }
  return _cacheItem;
}
function getIsAutoClose(cacheItem, isAutoAllocationOn) {
  var _a, _b, _c, _d, _e;
  if ((0, import_resourceSelection.productNeedsResourceExtend)(cacheItem) && !(0, import_resourceSelection.hasActualResourceSelection)(cacheItem)) {
    return false;
  }
  if (((_b = (_a = cacheItem._data) == null ? void 0 : _a.capacitys) == null ? void 0 : _b.type) !== "custom") {
    const resources = ((_c = cacheItem == null ? void 0 : cacheItem._data) == null ? void 0 : _c.resources) || [];
    if (resources.length === 1) {
      const first = resources[0];
      if (((_d = first.select_type) == null ? void 0 : _d.type) === "single" && (first.default_resource || []).length > 0) {
        return true;
      }
    }
  }
  const entries = Object.entries(((_e = cacheItem._extend) == null ? void 0 : _e.resource) || {});
  if (entries.length === 0) {
    return !(0, import_resourceSelection.productNeedsResourceExtend)(cacheItem);
  }
  return entries.every(
    ([key, value]) => isAutoAllocationOn(key) && Array.isArray(value) && value.length > 0
  );
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  derivePresetStartTimeFromDate,
  getIsAutoClose,
  getProductExtend,
  getServiceStartTimeAndEndTime,
  getSumCapacity,
  getTimeObj
});
