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/hudDrawerLocalListQuery.ts
var hudDrawerLocalListQuery_exports = {};
__export(hudDrawerLocalListQuery_exports, {
  applyHudDrawerLocalListQuery: () => applyHudDrawerLocalListQuery,
  cloneHudDrawerSearchParams: () => cloneHudDrawerSearchParams,
  mergeHudDrawerSearchParams: () => mergeHudDrawerSearchParams,
  stripHudDrawerBookingDateQuickFilter: () => stripHudDrawerBookingDateQuickFilter,
  stripHudDrawerBucketFilterDefaults: () => stripHudDrawerBucketFilterDefaults
});
module.exports = __toCommonJS(hudDrawerLocalListQuery_exports);
var import_dayjs = __toESM(require("dayjs"));
var import_perspectiveUtils = require("../../pisellSalesManagement/hooks/perspectiveUtils");
var import_bookingToReservationTables = require("./bookingToReservationTables");
var import_reservationDataUtils = require("./reservationDataUtils");
function cloneHudDrawerSearchParams(params) {
  try {
    return JSON.parse(JSON.stringify(params ?? {}));
  } catch {
    return { ...params ?? {} };
  }
}
function stripHudDrawerBookingDateQuickFilter(params) {
  const f = params.filter;
  if (typeof f !== "object" || f === null || Array.isArray(f)) {
    return;
  }
  const fo = f;
  const v = fo.values;
  if (typeof v !== "object" || v === null || Array.isArray(v)) {
    return;
  }
  const values = { ...v };
  delete values.booking_time_start_between;
  params.filter = { ...fo, values };
}
function stripHudDrawerBucketFilterDefaults(params) {
  const f = params.filter;
  if (typeof f !== "object" || f === null || Array.isArray(f)) {
    return;
  }
  const fo = f;
  const v = fo.values;
  if (typeof v !== "object" || v === null || Array.isArray(v)) {
    return;
  }
  const values = { ...v };
  values.appointment_status = [];
  values.order_payment_status = [];
  values.form_record_ids = [];
  params.filter = { ...fo, values };
}
function mergeHudDrawerSearchParams(prev, incoming) {
  const next = { ...prev, ...incoming };
  const prevFilter = typeof prev.filter === "object" && prev.filter !== null ? prev.filter : {};
  if (typeof incoming.filter === "object" && incoming.filter !== null && !Array.isArray(incoming.filter)) {
    const incFilter = incoming.filter;
    const prevV = typeof prevFilter.values === "object" && prevFilter.values !== null && !Array.isArray(prevFilter.values) ? prevFilter.values : {};
    const incV = typeof incFilter.values === "object" && incFilter.values !== null && !Array.isArray(incFilter.values) ? incFilter.values : void 0;
    next.filter = {
      ...prevFilter,
      ...incFilter,
      values: incV != null ? { ...prevV, ...incV } : prevV
    };
  }
  return (0, import_reservationDataUtils.mergeGridBookingSearchParams)(next);
}
function getRowStartMs(row) {
  const sa = row.start_at;
  if (typeof sa === "string" && sa) {
    const d = (0, import_dayjs.default)(sa);
    if (d.isValid()) return d.valueOf();
  }
  const ds = row.start_date;
  const ts = row.start_time;
  const comb = (0, import_perspectiveUtils.buildDateTime)(ds, ts);
  if (comb) {
    const d = (0, import_dayjs.default)(comb);
    if (d.isValid()) return d.valueOf();
  }
  return 0;
}
function getRowEndMs(row) {
  const ea = row.end_at;
  if (typeof ea === "string" && ea) {
    const d = (0, import_dayjs.default)(ea);
    if (d.isValid()) return d.valueOf();
  }
  const de = row.end_date;
  const te = row.end_time;
  const comb = (0, import_perspectiveUtils.buildDateTime)(de, te);
  if (comb) {
    const d = (0, import_dayjs.default)(comb);
    if (d.isValid()) return d.valueOf();
  }
  return 0;
}
function getRowCreatedMs(row) {
  const c = row.created_at;
  if (typeof c === "string" && c) {
    const d = (0, import_dayjs.default)(c);
    if (d.isValid()) return d.valueOf();
  }
  return 0;
}
function normalizeRangeBounds(raw) {
  if (!Array.isArray(raw) || raw.length < 2) return null;
  const a = (0, import_dayjs.default)(raw[0]);
  const b = (0, import_dayjs.default)(raw[1]);
  if (!a.isValid() || !b.isValid()) return null;
  const t0 = a.valueOf();
  const t1 = b.valueOf();
  return t0 <= t1 ? [t0, t1] : [t1, t0];
}
function multiSelectMatch(rowVals, selected) {
  if (!Array.isArray(selected) || selected.length === 0) return true;
  const set = new Set(selected.map((x) => String(x)));
  if (Array.isArray(rowVals)) {
    return rowVals.some((x) => set.has(String(x)));
  }
  if (rowVals == null || rowVals === "") return false;
  return set.has(String(rowVals));
}
function numberRangeContains(n, raw) {
  if (raw == null || typeof raw !== "object" || Array.isArray(raw)) {
    return true;
  }
  const o = raw;
  const minN = o.min != null && o.min !== "" ? Number(o.min) : NaN;
  const maxN = o.max != null && o.max !== "" ? Number(o.max) : NaN;
  const hasMin = Number.isFinite(minN);
  const hasMax = Number.isFinite(maxN);
  if (!hasMin && !hasMax) return true;
  if (!Number.isFinite(n)) return false;
  if (hasMin && n < minN) return false;
  if (hasMax && n > maxN) return false;
  return true;
}
function parseAmount(v) {
  if (v == null || v === "") return null;
  if (typeof v === "number" && Number.isFinite(v)) return v;
  const n = Number(String(v).replace(/,/g, "").trim());
  return Number.isFinite(n) ? n : null;
}
function paymentStatusForMatch(row) {
  const order = row.order;
  const st = (order == null ? void 0 : order.payment_status) ?? row.payment_status;
  const s = String(st ?? "").trim().toLowerCase();
  if (s === "partially_paid") return "unpaid";
  return s;
}
function rowMatchesKeyword(row, keyword) {
  const k = keyword.trim().toLowerCase();
  if (!k) return true;
  const acc = [];
  const push = (v) => {
    if (v == null) return;
    const s = String(v).toLowerCase().trim();
    if (s) acc.push(s);
  };
  push(row.id);
  push(row.booking_id);
  const order = row.order;
  if (order) {
    push(order.shop_full_order_number);
    push(order.note);
    const cust = order.customer;
    if (cust) {
      push(cust.name);
      push(cust.first_name);
      push(cust.last_name);
      push(cust.company_name);
    }
    const ci = order.contacts_info;
    if (ci) {
      push(ci.first_name);
      push(ci.last_name);
      push(ci.phone);
      push(ci.email);
    }
  }
  push(row.notes);
  return acc.some((p) => p.includes(k));
}
function rowMatchesValues(row, values) {
  var _a;
  const payment = values.order_payment_status;
  if (Array.isArray(payment) && payment.length > 0) {
    const st = paymentStatusForMatch(row);
    const allowed = new Set(payment.map((x) => String(x).toLowerCase()));
    if (st === "" || !allowed.has(st)) {
      return false;
    }
  }
  const appt = values.appointment_status;
  if (Array.isArray(appt) && appt.length > 0) {
    if (!multiSelectMatch(row.appointment_status, appt)) {
      return false;
    }
  }
  const orderStatus = values.order_status;
  if (Array.isArray(orderStatus) && orderStatus.length > 0) {
    const order2 = row.order;
    if (!multiSelectMatch((order2 == null ? void 0 : order2.order_status) ?? (order2 == null ? void 0 : order2.status), orderStatus)) {
      return false;
    }
  }
  const salesCh = values.order_sales_channel;
  if (Array.isArray(salesCh) && salesCh.length > 0) {
    const order2 = row.order;
    if (!multiSelectMatch(order2 == null ? void 0 : order2.order_sales_channel, salesCh)) {
      return false;
    }
  }
  const payMethod = values.payment_method;
  if (Array.isArray(payMethod) && payMethod.length > 0) {
    const order2 = row.order;
    const rowPm = (order2 == null ? void 0 : order2.payment_method) ?? (order2 == null ? void 0 : order2.pay_method) ?? (order2 == null ? void 0 : order2.payment_methods);
    if (!multiSelectMatch(rowPm, payMethod)) {
      return false;
    }
  }
  const custFilter = values.customer_id;
  if (Array.isArray(custFilter) && custFilter.length > 0) {
    const order2 = row.order;
    const cid = (order2 == null ? void 0 : order2.customer_id) ?? ((_a = order2 == null ? void 0 : order2.customer) == null ? void 0 : _a.id);
    if (cid == null || !custFilter.map(String).includes(String(cid))) {
      return false;
    }
  }
  const formIds = values.form_record_ids;
  if (Array.isArray(formIds) && formIds.length > 0) {
    const need = new Set(formIds.map((x) => String(x)));
    const got = (0, import_bookingToReservationTables.extractResourceRecordIds)(row);
    if (!got.some((id) => need.has(id))) {
      return false;
    }
  }
  const numBetween = values.number_between;
  if (numBetween != null && typeof numBetween === "object") {
    const party = typeof row.number === "number" && Number.isFinite(row.number) ? row.number : Number(row.number);
    if (!numberRangeContains(Number.isFinite(party) ? party : NaN, numBetween)) {
      return false;
    }
  }
  const order = row.order;
  const sum = order == null ? void 0 : order.summary;
  const amtBetween = values.total_amount_between;
  if (amtBetween != null && typeof amtBetween === "object") {
    const amt = parseAmount(sum == null ? void 0 : sum.total_amount) ?? parseAmount(order == null ? void 0 : order.total_amount) ?? parseAmount(row.amount ?? row.total);
    if (amt == null || !numberRangeContains(amt, amtBetween)) {
      return false;
    }
  }
  const createdR = normalizeRangeBounds(values.created_at_between);
  if (createdR) {
    const cm = getRowCreatedMs(row);
    if (cm === 0) return false;
    const [t0, t1] = createdR;
    if (cm < t0 || cm > t1) return false;
  }
  const updatedRaw = row.updated_at;
  const updatedR = normalizeRangeBounds(values.updated_at_between);
  if (updatedR) {
    const u = typeof updatedRaw === "string" && updatedRaw ? (0, import_dayjs.default)(updatedRaw).valueOf() : 0;
    if (!u) return false;
    const [t0, t1] = updatedR;
    if (u < t0 || u > t1) return false;
  }
  const range = normalizeRangeBounds(values.booking_time_start_between);
  if (range) {
    const [t0, t1] = range;
    const startMs = getRowStartMs(row);
    if (startMs === 0) return false;
    if (startMs < t0 || startMs > t1) return false;
  }
  return true;
}
function applySort(rows, sortKey) {
  if (!sortKey || !String(sortKey).includes(":")) {
    return rows;
  }
  const [field, dir] = String(sortKey).split(":");
  const desc = dir === "desc";
  const list = [...rows];
  const pick = (r) => {
    switch (field) {
      case "start_at":
      case "after_execution_time":
        return getRowStartMs(r);
      case "end_at":
        return getRowEndMs(r);
      case "created_at":
        return getRowCreatedMs(r);
      default:
        return 0;
    }
  };
  list.sort((a, b) => {
    const da = pick(a);
    const db = pick(b);
    if (da === db) return 0;
    return desc ? db - da : da - db;
  });
  return list;
}
function applyHudDrawerLocalListQuery(rows, searchParams) {
  let out = rows;
  const kw = searchParams.keyword;
  if (typeof kw === "string" && kw.trim()) {
    out = out.filter((r) => rowMatchesKeyword(r, kw));
  }
  const filter = searchParams.filter;
  const valuesRaw = filter && typeof filter === "object" && filter !== null && typeof filter.values === "object" && filter.values !== null && !Array.isArray(filter.values) ? filter.values : {};
  const values = valuesRaw;
  if (Object.keys(values).length > 0) {
    out = out.filter((r) => rowMatchesValues(r, values));
  }
  const sort = searchParams.sort;
  if (typeof sort === "string" && sort) {
    out = applySort(out, sort);
  }
  return out;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  applyHudDrawerLocalListQuery,
  cloneHudDrawerSearchParams,
  mergeHudDrawerSearchParams,
  stripHudDrawerBookingDateQuickFilter,
  stripHudDrawerBucketFilterDefaults
});
