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/calendarAdapter.ts
var calendarAdapter_exports = {};
__export(calendarAdapter_exports, {
  buildCalendarResourcesFromMergedTables: () => buildCalendarResourcesFromMergedTables,
  dayjsFromCalendarHour: () => dayjsFromCalendarHour,
  extractFloorMapSourceBookingForRow: () => extractFloorMapSourceBookingForRow,
  findMergedTableRowForBookingRaw: () => findMergedTableRowForBookingRaw,
  mapFloorDayBookingsToCalendarItems: () => mapFloorDayBookingsToCalendarItems,
  orderedCanvasResourceRecordIdStrings: () => orderedCanvasResourceRecordIdStrings
});
module.exports = __toCommonJS(calendarAdapter_exports);
var import_dayjs = __toESM(require("dayjs"));
var import_floorMapBoundRecordIds = require("../floorMap/floorMapBoundRecordIds");
var import_bookingToReservationTables = require("./bookingToReservationTables");
function parseBookingStart(b) {
  const raw = b.start_at || (b.start_date && b.start_time ? `${b.start_date} ${b.start_time}` : "");
  if (!raw) return null;
  const d = (0, import_dayjs.default)(raw);
  return d.isValid() ? d : null;
}
function parseBookingEnd(b) {
  const raw = b.end_at || (b.end_date && b.end_time ? `${b.end_date} ${b.end_time}` : "");
  if (!raw) return null;
  const d = (0, import_dayjs.default)(raw);
  return d.isValid() ? d : null;
}
function calendarDisplayEnd(b, start) {
  const explicit = parseBookingEnd(b);
  if (explicit) return explicit;
  const st = String(
    b.status ?? b.booking_status ?? b.order_status ?? ""
  ).trim().toLowerCase();
  if (st === "occupied" || st === "locked") {
    return start.endOf("day");
  }
  return start.add(2, "hour");
}
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 statusToCalendarTag(b) {
  const st = String(
    b.status ?? b.booking_status ?? b.order_status ?? ""
  ).trim().toLowerCase();
  if (st === "locked") return "block";
  if (st === "occupied") return "checked_in";
  if (st === "reserved") {
    const rs = String(b.reserved_status ?? "");
    if (rs === "late") return "late";
    return "new";
  }
  return void 0;
}
function fractionHourOf(d, dayStart) {
  return d.diff(dayStart, "minute", true) / 60;
}
function dayjsFromCalendarHour(dateStr, hourFloat) {
  const h = Math.floor(hourFloat);
  const m = Math.round((hourFloat - h) * 60);
  const mm = Math.min(59, Math.max(0, m));
  return (0, import_dayjs.default)(
    `${dateStr} ${String(h).padStart(2, "0")}:${String(mm).padStart(2, "0")}`,
    "YYYY-MM-DD HH:mm"
  );
}
function orderedCanvasResourceRecordIdStrings(sceneElements, gridDataSourceKey) {
  return (0, import_floorMapBoundRecordIds.sceneElementsToBoundRecordIdStrings)(sceneElements, gridDataSourceKey);
}
function buildCalendarResourcesFromMergedTables(options) {
  const { orderedResourceIds, tables } = options;
  const byId = new Map(tables.map((r) => [String(r.id), r]));
  return orderedResourceIds.map((id) => {
    const row = byId.get(id);
    return {
      id,
      name: (row == null ? void 0 : row.code) || (row == null ? void 0 : row.main_field) || id,
      groupType: row == null ? void 0 : row.area,
      form_id: id
    };
  });
}
function findMergedTableRowForBookingRaw(raw, tables) {
  const bid = String(
    raw.booking_id ?? raw.booking_uid ?? raw.id ?? ""
  ).trim();
  if (!bid) return void 0;
  for (const row of tables) {
    const list = row.floorMapSourceBookings;
    if (!Array.isArray(list)) continue;
    if (list.some((bk) => {
      const r = bk;
      const id = String(r.id ?? "").trim();
      const bookingId = String(r.booking_id ?? "").trim();
      const bookingUid = String(r.booking_uid ?? "").trim();
      return id === bid || bookingId === bid || bookingUid === bid;
    })) {
      return row;
    }
  }
  return void 0;
}
function extractFloorMapSourceBookingForRow(raw, row) {
  const bid = String(
    raw.booking_id ?? raw.booking_uid ?? raw.id ?? ""
  ).trim();
  if (!bid) return void 0;
  const list = row.floorMapSourceBookings;
  if (!Array.isArray(list)) return void 0;
  for (const bk of list) {
    if (!bk || typeof bk !== "object") continue;
    const r = bk;
    const id = String(r.id ?? "").trim();
    const bookingId = String(r.booking_id ?? "").trim();
    const bookingUid = String(r.booking_uid ?? "").trim();
    if (id === bid || bookingId === bid || bookingUid === bid) {
      return r;
    }
  }
  return void 0;
}
function mapFloorDayBookingsToCalendarItems(options) {
  const { bookings, canvasResourceIdSet } = options;
  if (!Array.isArray(bookings)) return [];
  const filterByCanvas = canvasResourceIdSet.size > 0;
  const out = [];
  let seq = 0;
  for (const raw of bookings) {
    if (!raw || typeof raw !== "object") continue;
    const b = raw;
    if (isAggregateParentShell(b)) continue;
    const rids = (0, import_bookingToReservationTables.extractResourceRecordIds)(b).filter(
      (id) => filterByCanvas ? canvasResourceIdSet.has(id) : Boolean(id)
    );
    if (rids.length === 0) continue;
    const start = parseBookingStart(b);
    if (!start) continue;
    const end = calendarDisplayEnd(b, start);
    if (!end.isAfter(start)) continue;
    const name = (0, import_bookingToReservationTables.customerBrief)(b) || String(b.relation_form_name ?? b.booking_id ?? "Booking");
    const phoneRaw = b.phone ?? b.mobile ?? b.customer_phone;
    const phone = typeof phoneRaw === "string" ? phoneRaw : void 0;
    const statusTag = statusToCalendarTag(b);
    const baseId = String(b.booking_id ?? b.id ?? `bk_${seq++}`);
    const statusNorm = String(
      b.status ?? b.booking_status ?? b.order_status ?? ""
    ).trim().toLowerCase();
    const kind = statusNorm === "locked" ? "block" : "booking";
    const startDayStart = start.startOf("day");
    const startHour = fractionHourOf(start, startDayStart);
    const endDayStart = end.startOf("day");
    const endIsExactMidnight = end.hour() === 0 && end.minute() === 0 && end.second() === 0;
    const effectiveEndDayStart = endIsExactMidnight ? endDayStart.subtract(1, "day") : endDayStart;
    const endHour = endIsExactMidnight ? 24 : fractionHourOf(end, effectiveEndDayStart);
    const dateStr = startDayStart.format("YYYY-MM-DD");
    const endDateStr = effectiveEndDayStart.format("YYYY-MM-DD");
    for (const courtId of rids) {
      out.push({
        id: `${baseId}_${courtId}`,
        courtId,
        date: dateStr,
        startHour,
        endDate: endDateStr === dateStr ? void 0 : endDateStr,
        endHour,
        name,
        kind,
        phone,
        statusTag,
        raw: b
      });
    }
  }
  const seen = /* @__PURE__ */ new Set();
  const dedup = [];
  for (const it of out) {
    if (seen.has(it.id)) continue;
    seen.add(it.id);
    dedup.push(it);
  }
  return dedup;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  buildCalendarResourcesFromMergedTables,
  dayjsFromCalendarHour,
  extractFloorMapSourceBookingForRow,
  findMergedTableRowForBookingRaw,
  mapFloorDayBookingsToCalendarItems,
  orderedCanvasResourceRecordIdStrings
});
