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/plus/pisellReservation/data/bookingToReservationTables.ts
var bookingToReservationTables_exports = {};
__export(bookingToReservationTables_exports, {
  applyHostResourceShellToBaseRow: () => applyHostResourceShellToBaseRow,
  bookingListToReservationTableRows: () => bookingListToReservationTableRows,
  bookingReferenceDay: () => bookingReferenceDay,
  customerBrief: () => customerBrief,
  extractResourceRecordIds: () => extractResourceRecordIds,
  filterBookingsByResourceIds: () => filterBookingsByResourceIds,
  formatBookingTime: () => formatBookingTime,
  hostBookingStatusToCardStatus: () => hostBookingStatusToCardStatus,
  hostBookingUiPatchFromRecord: () => hostBookingUiPatchFromRecord,
  isMonitorScheduleBookingSkipped: () => isMonitorScheduleBookingSkipped,
  mergeBookingsForResourceRecord: () => mergeBookingsForResourceRecord,
  sortBookingsByStartTime: () => sortBookingsByStartTime
});
module.exports = __toCommonJS(bookingToReservationTables_exports);
var import_dayjs = __toESM(require("dayjs"));
var import_mapRowToFloorRoomCardData = require("../floorRoomCard/mapRowToFloorRoomCardData");
function isMonitorScheduleBookingSkipped(record) {
  const raw = record.status ?? record.booking_status ?? record.order_status ?? "";
  const s = String(raw).trim().toLowerCase();
  if (!s) return false;
  if (s === "empty") return true;
  return s !== "reserved" && s !== "occupied" && s !== "locked";
}
function collectRelationIdsFromNode(node, ids) {
  if (!node) return;
  const rid = node.relation_id;
  if (typeof rid === "number" && rid > 0) ids.add(String(Math.trunc(rid)));
  else if (typeof rid === "string" && rid !== "" && rid !== "0") ids.add(rid);
  const kids = node.children;
  if (Array.isArray(kids)) {
    for (const ch of kids) {
      collectRelationIdsFromNode(ch, ids);
    }
  }
}
function extractResourceRecordIds(booking) {
  const ids = /* @__PURE__ */ new Set();
  const er = booking.event_resources;
  if (Array.isArray(er)) {
    for (const block of er) {
      collectRelationIdsFromNode(block, ids);
    }
  }
  const res = booking.resources;
  if (Array.isArray(res)) {
    for (const block of res) {
      collectRelationIdsFromNode(block, ids);
    }
  }
  return [...ids];
}
function filterBookingsByResourceIds(bookings, resourceIds) {
  if (!Array.isArray(bookings) || resourceIds.size === 0) {
    return [];
  }
  return bookings.filter((b) => {
    const ids = extractResourceRecordIds(b);
    return ids.some((id) => resourceIds.has(id));
  });
}
function isAggregateParentShell(booking) {
  const meta = booking.metadata;
  if ((meta == null ? void 0 : meta.multiple_resource_flag) !== 1) return false;
  const uid = booking.product_uid;
  if (uid != null && String(uid) !== "") return false;
  const res = booking.resources;
  return !Array.isArray(res) || res.length === 0;
}
function resourceDisplayCode(booking) {
  const name = booking.relation_form_name;
  if (name) return name;
  const er0 = Array.isArray(booking.event_resources) ? booking.event_resources[0] : void 0;
  const res0 = Array.isArray(booking.resources) ? booking.resources[0] : void 0;
  const head = er0 ?? res0;
  const meta = head == null ? void 0 : head.metadata;
  const rn = (meta == null ? void 0 : meta.resource_name) ?? (meta == null ? void 0 : meta.form_name);
  if (typeof rn === "string" && rn) return rn;
  const bid = booking.booking_id;
  if (bid != null && bid !== "") return String(bid);
  return String(booking.id ?? "");
}
function customerBrief(record) {
  var _a;
  const h = (0, import_mapRowToFloorRoomCardData.resolveFloorRoomCardHolder)(record);
  const n = (_a = h == null ? void 0 : h.name) == null ? void 0 : _a.trim();
  return n || "";
}
function bookingReferenceDay(booking) {
  const at = booking.start_at;
  if (at && (0, import_dayjs.default)(at).isValid()) return (0, import_dayjs.default)(at).format("YYYY-MM-DD");
  const sd = booking.start_date;
  if (typeof sd === "string" && /^\d{4}-\d{2}-\d{2}/.test(sd))
    return sd.slice(0, 10);
  return void 0;
}
function formatBookingTime(record) {
  const raw = record.start_at || (record.start_date && record.start_time ? `${record.start_date} ${record.start_time}` : null);
  if (!raw) return "";
  const d = (0, import_dayjs.default)(raw);
  return d.isValid() ? d.format("HH:mm") : "";
}
function sortBookingsByStartTime(bookings) {
  return [...bookings].sort(
    (a, b) => (0, import_dayjs.default)(
      a.start_at || `${String(a.start_date ?? "")} ${String(a.start_time ?? "")}`.trim()
    ).valueOf() - (0, import_dayjs.default)(
      b.start_at || `${String(b.start_date ?? "")} ${String(b.start_time ?? "")}`.trim()
    ).valueOf()
  );
}
function hostBookingStatusToCardStatus(record) {
  const s = String(record.status ?? "");
  if (s === "occupied") return "occupied";
  if (s === "reserved") return "booked";
  if (s === "locked") return "maintenance";
  return "available";
}
function hostReservedStatusFromBooking(booking) {
  if (String(booking.status) !== "reserved") return void 0;
  const rs = String(booking.reserved_status ?? "");
  if (rs === "late") return "late";
  if (rs === "not_arrived") return "not_arrived";
  return void 0;
}
function hostIsTimeoutFromBooking(booking) {
  if (String(booking.status) !== "occupied") return void 0;
  return booking.isTimeout === true ? true : void 0;
}
function hostBookingUiPatchFromRecord(booking) {
  const hostReservedStatus = hostReservedStatusFromBooking(booking);
  const hostIsTimeout = hostIsTimeoutFromBooking(booking);
  const out = {};
  if (hostReservedStatus != null) out.hostReservedStatus = hostReservedStatus;
  if (hostIsTimeout === true) out.hostIsTimeout = true;
  return out;
}
function applyHostResourceShellToBaseRow(base, shell) {
  const st = String(shell.status ?? "");
  if (st === "locked") {
    return { ...base, cardStatus: "maintenance" };
  }
  if (st === "empty") {
    return {
      ...base,
      cardStatus: "available",
      hostReservedStatus: void 0,
      hostIsTimeout: void 0
    };
  }
  if (st === "occupied") {
    return {
      ...base,
      cardStatus: "occupied",
      hostIsTimeout: shell.isTimeout === true ? true : void 0,
      hostReservedStatus: void 0
    };
  }
  if (st === "reserved") {
    return {
      ...base,
      cardStatus: "booked",
      hostIsTimeout: void 0,
      ...hostBookingUiPatchFromRecord(shell)
    };
  }
  return base;
}
function singleBookingToRow(rowId, booking, codeOverride) {
  const code = codeOverride ?? resourceDisplayCode(booking);
  return {
    id: rowId,
    code,
    cardStatus: hostBookingStatusToCardStatus(booking),
    ...hostBookingUiPatchFromRecord(booking),
    guestName: customerBrief(booking) || void 0,
    time: formatBookingTime(booking) || void 0,
    floorMapSourceBookings: [booking],
    floorMapReferenceDay: bookingReferenceDay(booking),
    partySize: (() => {
      const n = booking.number;
      if (typeof n === "number" && Number.isFinite(n)) return n;
      if (n != null && n !== "") {
        const v = Number(n);
        return Number.isFinite(v) ? v : void 0;
      }
      return void 0;
    })()
  };
}
function mergeResourceGroup(recordId, group) {
  const named = group.find((g) => g.relation_form_name);
  const code = (named == null ? void 0 : named.relation_form_name) ? String(named.relation_form_name) : resourceDisplayCode(group[0]);
  const sorted = sortBookingsByStartTime(group);
  if (sorted.length === 1) {
    return singleBookingToRow(recordId, sorted[0], code);
  }
  const hasLocked = sorted.some((b) => String(b.status) === "locked");
  const hasOccupied = sorted.some((b) => String(b.status) === "occupied");
  const cardStatus = hasLocked ? "maintenance" : hasOccupied ? "occupied" : "booked";
  const uiPatch = {};
  if (cardStatus === "occupied") {
    const ob = sorted.find((b) => String(b.status) === "occupied");
    if (ob && hostIsTimeoutFromBooking(ob)) uiPatch.hostIsTimeout = true;
  }
  if (cardStatus === "booked") {
    const rb = sorted.find((b) => String(b.status) === "reserved");
    const rs = rb ? hostReservedStatusFromBooking(rb) : void 0;
    if (rs != null) uiPatch.hostReservedStatus = rs;
  }
  return {
    id: recordId,
    code: code || recordId,
    cardStatus,
    ...cardStatus === "maintenance" ? { hostReservedStatus: void 0, hostIsTimeout: void 0 } : uiPatch,
    floorMapSourceBookings: sorted,
    floorMapReferenceDay: bookingReferenceDay(sorted[0]),
    slots: sorted.map((b) => ({
      name: customerBrief(b) || "",
      time: formatBookingTime(b) || "-"
    }))
  };
}
function mergeBookingsForResourceRecord(recordId, bookings) {
  if (!Array.isArray(bookings)) return null;
  const active = bookings.filter((b) => {
    if (!b || typeof b !== "object") return false;
    const rec = b;
    if (isMonitorScheduleBookingSkipped(rec)) return false;
    if (isAggregateParentShell(rec)) return false;
    return true;
  });
  if (active.length === 0) return null;
  return mergeResourceGroup(recordId, active);
}
function bookingListToReservationTableRows(bookings) {
  if (!Array.isArray(bookings) || bookings.length === 0) return [];
  const active = bookings.filter((b) => {
    if (!b || typeof b !== "object") return false;
    const rec = b;
    if (isMonitorScheduleBookingSkipped(rec)) return false;
    if (isAggregateParentShell(rec)) return false;
    return true;
  });
  const byResource = /* @__PURE__ */ new Map();
  const orphans = [];
  for (const b of active) {
    const rids = extractResourceRecordIds(b);
    if (rids.length > 0) {
      for (const rid of rids) {
        const g = byResource.get(rid) ?? [];
        g.push(b);
        byResource.set(rid, g);
      }
    } else {
      orphans.push(b);
    }
  }
  const rows = [];
  for (const [rid, group] of byResource) {
    rows.push(mergeResourceGroup(rid, group));
  }
  for (const b of orphans) {
    const id = b.id != null ? String(b.id) : `booking_${rows.length}`;
    rows.push(singleBookingToRow(id, b));
  }
  return rows;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  applyHostResourceShellToBaseRow,
  bookingListToReservationTableRows,
  bookingReferenceDay,
  customerBrief,
  extractResourceRecordIds,
  filterBookingsByResourceIds,
  formatBookingTime,
  hostBookingStatusToCardStatus,
  hostBookingUiPatchFromRecord,
  isMonitorScheduleBookingSkipped,
  mergeBookingsForResourceRecord,
  sortBookingsByStartTime
});
