var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/plus/pisellReservation/components/bookingChangeModal/utils.ts
var utils_exports = {};
__export(utils_exports, {
  alignBookingDraftToSlots: () => alignBookingDraftToSlots,
  asNumber: () => asNumber,
  asRecord: () => asRecord,
  asRecordList: () => asRecordList,
  asString: () => asString,
  buildCustomer: () => buildCustomer,
  buildScheduleResourceCourt: () => buildScheduleResourceCourt,
  buildSubmitPayload: () => buildSubmitPayload,
  buildSubmitResourcesFromEventResources: () => buildSubmitResourcesFromEventResources,
  defaultFormatHourLabel: () => defaultFormatHourLabel,
  getFallbackHourSlots: () => getFallbackHourSlots,
  getHourStep: () => getHourStep,
  getItemRaw: () => getItemRaw,
  getItemResourceRecords: () => getItemResourceRecords,
  getNormalizedDateTime: () => getNormalizedDateTime,
  getOrderId: () => getOrderId,
  getScheduleResourceList: () => getScheduleResourceList,
  mergeCourts: () => mergeCourts,
  nearestHourInSlots: () => nearestHourInSlots,
  normalizeCourt: () => normalizeCourt
});
module.exports = __toCommonJS(utils_exports);
function asRecord(value) {
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    return void 0;
  }
  return value;
}
function asRecordList(value) {
  if (!Array.isArray(value)) {
    return [];
  }
  return value.map((item) => asRecord(item)).filter(Boolean);
}
function asString(value) {
  if (value === void 0 || value === null || value === "") {
    return void 0;
  }
  return String(value);
}
function asNumber(value, fallback = 0) {
  const next = Number(value);
  return Number.isFinite(next) ? next : fallback;
}
function getMetadataRecord(source) {
  var _a;
  return asRecord((_a = asRecord(source)) == null ? void 0 : _a.metadata) || {};
}
function getCustomerIdentity(orderDetail) {
  return (orderDetail == null ? void 0 : orderDetail.customer_with_extra) || (orderDetail == null ? void 0 : orderDetail.customer);
}
function defaultFormatHourLabel(hour) {
  const normalizedMinutes = Math.round(hour * 60);
  const wholeHours = Math.floor(normalizedMinutes / 60);
  const minutes = normalizedMinutes % 60;
  return `${String(wholeHours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}`;
}
function getHourStep(hourSlots) {
  if (hourSlots.length < 2) {
    return 1;
  }
  const sorted = [...hourSlots].sort((a, b) => a - b);
  let minStep = Number.POSITIVE_INFINITY;
  for (let index = 1; index < sorted.length; index += 1) {
    const step = sorted[index] - sorted[index - 1];
    if (step > 0 && step < minStep) {
      minStep = step;
    }
  }
  return Number.isFinite(minStep) ? minStep : 1;
}
function getFallbackHourSlots() {
  return Array.from({ length: 24 }, (_, index) => index);
}
function nearestHourInSlots(hour, slots) {
  if (!Number.isFinite(hour) || slots.length === 0) return hour;
  let best = slots[0];
  let bestDist = Math.abs(hour - best);
  for (const slot of slots) {
    const distance = Math.abs(hour - slot);
    if (distance < bestDist - 1e-9) {
      bestDist = distance;
      best = slot;
    }
  }
  return best;
}
function alignBookingDraftToSlots(targetHour, durationHours, slots) {
  if (!Number.isFinite(durationHours) || durationHours < 0 || slots.length === 0) {
    return targetHour;
  }
  const endRaw = targetHour + durationHours;
  const endAligned = nearestHourInSlots(endRaw, slots);
  let startAligned = nearestHourInSlots(endAligned - durationHours, slots);
  const endCheck = nearestHourInSlots(startAligned + durationHours, slots);
  startAligned = nearestHourInSlots(endCheck - durationHours, slots);
  return startAligned;
}
function formatDateKey(date) {
  const year = date.getFullYear();
  const month = `${date.getMonth() + 1}`.padStart(2, "0");
  const day = `${date.getDate()}`.padStart(2, "0");
  return `${year}-${month}-${day}`;
}
function getNormalizedDateTime(dateKey, hour) {
  const date = /* @__PURE__ */ new Date(`${dateKey}T00:00:00`);
  if (Number.isNaN(date.getTime())) {
    return {
      date: dateKey,
      time: defaultFormatHourLabel(hour)
    };
  }
  const minutes = Math.round(hour * 60);
  date.setMinutes(date.getMinutes() + minutes);
  return {
    date: formatDateKey(date),
    time: `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(
      2,
      "0"
    )}`
  };
}
function normalizeCombinedResource(value) {
  const record = asRecord(value);
  if (!record || !Array.isArray(record.resource_ids)) {
    return void 0;
  }
  return {
    status: asNumber(record.status, 0),
    resource_ids: record.resource_ids.map((resourceId) => Number(resourceId)).filter((resourceId) => Number.isFinite(resourceId))
  };
}
function getItemRaw(item) {
  return asRecord(item.raw) || {};
}
function getOrderId(item) {
  const raw = getItemRaw(item);
  const orderId = raw.order_id;
  if (typeof orderId === "string" || typeof orderId === "number") {
    return orderId;
  }
  return null;
}
function getItemResourceRecords(item) {
  const rawResources = asRecordList(getItemRaw(item).resources);
  if (rawResources.length > 0) {
    return rawResources.map(normalizeResourceNode);
  }
  return asRecordList(item.resources).map(normalizeResourceNode);
}
function normalizeResourceNode(resource) {
  return {
    form_id: resource.form_id,
    relation_type: resource.relation_type,
    relation_id: resource.relation_id,
    capacity: asNumber(resource.capacity, 0),
    like_status: resource.like_status,
    metadata: getMetadataRecord(resource),
    children: asRecordList(resource.children).map(normalizeResourceNode)
  };
}
function normalizeCourt(court) {
  return {
    id: court.id,
    name: court.name,
    form_id: court.form_id,
    relation_id: court.relation_id,
    relation_type: court.relation_type,
    resource_id: court.resource_id,
    capacity: asNumber(court.capacity, 0),
    like_status: court.like_status,
    metadata: getMetadataRecord(court),
    raw: asRecord(court.raw)
  };
}
function getScheduleResourceList(response) {
  if (Array.isArray(response)) {
    return asRecordList(response);
  }
  const record = asRecord(response);
  if (Array.isArray(record == null ? void 0 : record.list)) {
    return asRecordList(record.list);
  }
  if (Array.isArray(record == null ? void 0 : record.data)) {
    return asRecordList(record.data);
  }
  return [];
}
function buildScheduleResourceCourt(resource, formName) {
  const id = asString(resource.id);
  const name = asString(resource.main_field);
  if (!id || !name) {
    return null;
  }
  const combinedResource = normalizeCombinedResource(resource.combined_resource);
  return {
    id,
    name,
    form_id: resource.form_id,
    relation_id: resource.id,
    resource_id: resource.id,
    relation_type: "form",
    capacity: asNumber(resource.capacity, 0),
    like_status: "common",
    metadata: {
      form_name: formName,
      resource_name: name,
      ...combinedResource ? { combined_resource: combinedResource } : {}
    },
    raw: resource
  };
}
function mergeCourts(lists) {
  const merged = /* @__PURE__ */ new Map();
  for (const list of lists) {
    for (const court of list) {
      if (!(court == null ? void 0 : court.id)) {
        continue;
      }
      merged.set(court.id, {
        ...merged.get(court.id),
        ...court,
        metadata: {
          ...getMetadataRecord(merged.get(court.id)),
          ...getMetadataRecord(court)
        }
      });
    }
  }
  return Array.from(merged.values());
}
function buildCombinedChildren(targetCourt, resourceCourtMap) {
  const combinedResource = normalizeCombinedResource(targetCourt.metadata.combined_resource);
  if (!combinedResource || combinedResource.resource_ids.length === 0) {
    return void 0;
  }
  const children = combinedResource.resource_ids.map((resourceId) => resourceCourtMap.get(String(resourceId))).filter((court) => Boolean(court)).map((court) => ({
    form_id: court.form_id,
    relation_type: court.relation_type,
    relation_id: court.relation_id,
    capacity: court.capacity,
    like_status: court.like_status,
    metadata: {
      ...court.metadata,
      form_name: court.metadata.form_name,
      resource_name: court.metadata.resource_name
    }
  }));
  return children.length > 0 ? children : void 0;
}
function buildChangedResource(originalResource, targetCourt, resourceCourtMap) {
  const metadata = {
    ...originalResource.metadata,
    ...targetCourt.metadata,
    form_name: targetCourt.metadata.form_name,
    resource_name: targetCourt.metadata.resource_name
  };
  const combinedResource = normalizeCombinedResource(targetCourt.metadata.combined_resource);
  if (combinedResource) {
    metadata.combined_resource = combinedResource;
  } else {
    delete metadata.combined_resource;
  }
  const children = buildCombinedChildren(targetCourt, resourceCourtMap);
  return {
    form_id: targetCourt.form_id,
    relation_type: targetCourt.relation_type,
    relation_id: targetCourt.relation_id,
    capacity: targetCourt.capacity,
    like_status: targetCourt.like_status,
    metadata,
    ...children ? { children } : {}
  };
}
function normalizeEventResourceForSubmit(res) {
  const children = asRecordList(res.children).map(normalizeEventResourceForSubmit);
  return {
    form_id: res.form_id,
    relation_type: res.relation_type || "form",
    relation_id: res.relation_id,
    capacity: asNumber(res.capacity, 0),
    like_status: res.like_status || "common",
    metadata: asRecord(res.metadata) || {},
    ...children.length > 0 ? { children } : {}
  };
}
function buildSubmitResourcesFromEventResources(eventResources, resourceCourtIds, resourceCourtMap) {
  return eventResources.map((res, i) => {
    const selectedId = resourceCourtIds[i];
    const originalId = String(res.relation_id);
    if (selectedId && selectedId !== originalId) {
      const targetCourt = resourceCourtMap.get(selectedId);
      if (targetCourt) {
        return buildChangedResource(normalizeResourceNode(res), targetCourt, resourceCourtMap);
      }
    }
    return normalizeEventResourceForSubmit(res);
  });
}
function getSubmitScheduleId(raw, orderDetail) {
  var _a;
  const rawScheduleId = raw.schedule_id;
  if (rawScheduleId !== void 0 && rawScheduleId !== null && rawScheduleId !== "") {
    return rawScheduleId;
  }
  const rawId = raw.id;
  if (rawId === void 0 || rawId === null || rawId === "") {
    return void 0;
  }
  const matchedBooking = (((_a = orderDetail == null ? void 0 : orderDetail.bookings) == null ? void 0 : _a.list) || []).find(
    (booking) => String(booking == null ? void 0 : booking.id) === String(rawId)
  );
  return matchedBooking == null ? void 0 : matchedBooking.schedule_id;
}
function buildSubmitPayload(args) {
  const {
    item,
    draft,
    duration,
    nextEndHour,
    currentEventResources,
    resourceCourtIds,
    resourceCourtMap,
    orderDetail
  } = args;
  const raw = getItemRaw(item);
  const rawMetadata = getMetadataRecord(raw);
  const start = getNormalizedDateTime(draft.targetDate, draft.targetHour);
  const end = getNormalizedDateTime(draft.targetDate, nextEndHour);
  const metadata = { ...rawMetadata };
  const resources = buildSubmitResourcesFromEventResources(
    currentEventResources,
    resourceCourtIds,
    resourceCourtMap
  );
  return {
    id: raw.id,
    relation_id: raw.relation_id,
    like_status: raw.like_status,
    relation_type: raw.relation_type,
    is_all: asNumber(raw.is_all, 0),
    schedule_id: getSubmitScheduleId(raw, orderDetail),
    sub_type: raw.sub_type,
    select_date: draft.targetDate,
    number: raw.number,
    metadata,
    resources,
    start_date: start.date,
    start_time: start.time,
    end_date: end.date,
    end_time: end.time,
    duration: Math.max(0, Math.round(duration * 60))
  };
}
function buildCustomer(args) {
  var _a;
  const { orderDetail, selectedCustomer, fallbackCustomerText } = args;
  if (selectedCustomer) {
    return selectedCustomer;
  }
  const customer = getCustomerIdentity(orderDetail);
  const contacts = orderDetail == null ? void 0 : orderDetail.contacts_info;
  return {
    name: (customer == null ? void 0 : customer.display_name) || (customer == null ? void 0 : customer.nickname) || fallbackCustomerText,
    phone: ((_a = contacts == null ? void 0 : contacts.phone) == null ? void 0 : _a.phone) || (customer == null ? void 0 : customer.phone) || "",
    email: (contacts == null ? void 0 : contacts.email) || (customer == null ? void 0 : customer.email) || "",
    memberId: (customer == null ? void 0 : customer.member_id) || ""
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  alignBookingDraftToSlots,
  asNumber,
  asRecord,
  asRecordList,
  asString,
  buildCustomer,
  buildScheduleResourceCourt,
  buildSubmitPayload,
  buildSubmitResourcesFromEventResources,
  defaultFormatHourLabel,
  getFallbackHourSlots,
  getHourStep,
  getItemRaw,
  getItemResourceRecords,
  getNormalizedDateTime,
  getOrderId,
  getScheduleResourceList,
  mergeCourts,
  nearestHourInSlots,
  normalizeCourt
});
