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/buildCacheItemFromOrderLine.ts
var buildCacheItemFromOrderLine_exports = {};
__export(buildCacheItemFromOrderLine_exports, {
  buildCacheItemFromOrderLine: () => buildCacheItemFromOrderLine
});
module.exports = __toCommonJS(buildCacheItemFromOrderLine_exports);
var import_dayjs = __toESM(require("dayjs"));
var import_utils = require("../../Order/utils");
var import_manualProductDiscount = require("../../Order/utils/manualProductDiscount");
var import_orderLineDisplay = require("./orderLineDisplay");
function safeFormat(value, fmt) {
  if (value === void 0 || value === null)
    return void 0;
  const d = (0, import_dayjs.default)(value);
  if (!d.isValid())
    return void 0;
  return d.format(fmt);
}
function normalizeTimeString(value) {
  if (value === void 0 || value === null)
    return void 0;
  if (typeof value === "string") {
    const t = value.trim();
    const hhmmFromHhmmss = t.match(/^(\d{1,2}:\d{2}):\d{2}$/);
    if (hhmmFromHhmmss)
      return hhmmFromHhmmss[1];
    if (/^\d{1,2}:\d{2}$/.test(t))
      return t;
  }
  const d = (0, import_dayjs.default)(value);
  if (d.isValid())
    return d.format("HH:mm");
  return void 0;
}
function unflattenResourceMap(resources) {
  const map = {};
  if (!Array.isArray(resources))
    return map;
  resources.forEach((r) => {
    const formId = r == null ? void 0 : r.form_id;
    if (formId === void 0 || formId === null)
      return;
    const key = String(formId);
    if (!map[key])
      map[key] = [];
    map[key].push({
      form_id: formId,
      relation_id: r.relation_id,
      relation_type: r.relation_type || "form",
      like_status: r.like_status || "common",
      metadata: r.metadata ? { ...r.metadata } : void 0,
      children: r.children
    });
  });
  return map;
}
function resolveCapacityFromBooking(booking) {
  var _a;
  const metaCap = (_a = booking.metadata) == null ? void 0 : _a.capacity;
  if (Array.isArray(metaCap) && metaCap.length > 0) {
    return metaCap.map((item) => {
      if (!item || typeof item !== "object")
        return null;
      if (item.id === void 0 || item.id === null)
        return null;
      const row = {
        id: item.id,
        value: Number(item.value ?? 0)
      };
      if (item.name !== void 0)
        row.name = item.name;
      return row;
    }).filter((item) => item != null);
  }
  if (typeof metaCap === "number" && Number.isFinite(metaCap)) {
    return [{ id: 0, value: metaCap, name: "" }];
  }
  return [];
}
function resolveDurationForExtend(booking) {
  const duration = booking.duration;
  if (booking.sub_type === "days" || booking.is_all === 1) {
    return duration;
  }
  if (typeof duration === "number" && Number.isFinite(duration)) {
    return duration;
  }
  return duration;
}
function resolveTopLevelDuration(booking, sourceProduct) {
  if ((sourceProduct == null ? void 0 : sourceProduct.duration) !== void 0) {
    return sourceProduct.duration;
  }
  const raw = booking.duration;
  if (raw == null || raw === "")
    return void 0;
  if (typeof raw === "object" && raw.type) {
    return raw;
  }
  const subType = booking.sub_type === "days" ? "days" : "minutes";
  const value = Number(raw);
  if (!Number.isFinite(value) || value <= 0)
    return void 0;
  return { type: subType, value };
}
function resolveProductTitle(product, booking, sourceProduct) {
  var _a, _b;
  const metadata = product.metadata || {};
  return (sourceProduct == null ? void 0 : sourceProduct.title) ?? (sourceProduct == null ? void 0 : sourceProduct.name) ?? metadata.product_title ?? metadata.product_name ?? ((_a = booking == null ? void 0 : booking.product) == null ? void 0 : _a.title) ?? ((_b = booking == null ? void 0 : booking.detail) == null ? void 0 : _b.product_title) ?? "";
}
function synthesizeProductResourceFromBooking(booking) {
  const rows = booking == null ? void 0 : booking.resources;
  if (!Array.isArray(rows) || rows.length === 0)
    return void 0;
  const relationIdsByForm = /* @__PURE__ */ new Map();
  rows.forEach((row) => {
    const formId = row == null ? void 0 : row.form_id;
    const relationId = Number(row == null ? void 0 : row.relation_id);
    if (formId == null || formId === "" || !Number.isFinite(relationId) || relationId <= 0) {
      return;
    }
    const list = relationIdsByForm.get(formId) ?? [];
    if (!list.includes(relationId)) {
      list.push(relationId);
    }
    relationIdsByForm.set(formId, list);
  });
  if (relationIdsByForm.size === 0)
    return void 0;
  return {
    resources: Array.from(relationIdsByForm.entries()).map(([formId, relationIds]) => ({
      id: formId,
      status: 1,
      type: "form",
      code: "",
      optional_resource: relationIds,
      default_resource: []
    }))
  };
}
function buildCacheItemFromOrderLine(input) {
  var _a, _b, _c, _d, _e, _f;
  const { product, booking, sourceProduct } = input;
  const resolvedId = product.product_id ?? (sourceProduct == null ? void 0 : sourceProduct.id);
  const selling = Number(product.selling_price ?? 0);
  const original = Number(product.original_price ?? selling);
  const startDate = safeFormat(booking.start_date, "YYYY-MM-DD");
  const endDate = safeFormat(booking.end_date, "YYYY-MM-DD");
  const startTime = normalizeTimeString(booking.start_time);
  const endTime = normalizeTimeString(booking.end_time);
  const resource = unflattenResourceMap(booking.resources);
  const capacity = resolveCapacityFromBooking(booking);
  const holderId = ((_a = booking.metadata) == null ? void 0 : _a.holder_id) ?? booking.holder_id;
  const productTitle = resolveProductTitle(product, booking, sourceProduct);
  const productOptionString = (0, import_orderLineDisplay.buildProductOptionStringFromOrderLine)(product);
  const other = {
    product_variant_id: product.product_variant_id ?? 0,
    option: (0, import_utils.getProductSkuOptions)(product),
    bundle: Array.isArray(product.product_bundle) ? [...product.product_bundle] : []
  };
  const extend = {
    start_date: startDate ? (0, import_dayjs.default)(startDate) : void 0,
    end_date: endDate ? (0, import_dayjs.default)(endDate) : void 0,
    startDate: startDate ? (0, import_dayjs.default)(startDate) : void 0,
    endDate: endDate ? (0, import_dayjs.default)(endDate) : void 0,
    start_time: startTime,
    end_time: endTime,
    duration: resolveDurationForExtend(booking),
    sub_type: booking.sub_type,
    quantity: product.num ?? 1,
    product_name: productTitle,
    note: product.note ?? ((_b = booking == null ? void 0 : booking.detail) == null ? void 0 : _b.note) ?? "",
    price: selling,
    total: selling,
    origin_total: original,
    resource,
    capacity,
    holder_id: holderId,
    other,
    like_status: booking.like_status || "common",
    discount_reason: (0, import_manualProductDiscount.resolveManualDiscountMessage)(
      product.discount_list,
      (_c = product.metadata) == null ? void 0 : _c.product_discount_reason
    ) || void 0,
    ...productOptionString ? { product_option_string: productOptionString } : {}
  };
  const manualDiscount = (product.discount_list || []).find((d) => (d == null ? void 0 : d.type) === "product");
  if (manualDiscount && extend.origin_total === selling) {
    const manualAmount = Number(manualDiscount.amount ?? 0);
    if (Number.isFinite(manualAmount) && manualAmount > 0) {
      extend.origin_total = selling + manualAmount;
    }
  }
  if (((_d = product.metadata) == null ? void 0 : _d.price_override) != null || manualDiscount) {
    extend.priceOverride = selling;
  }
  if (booking.holder !== void 0) {
    extend.holder = booking.holder;
  }
  if (Array.isArray(booking.relation_forms)) {
    extend.relation_forms = booking.relation_forms;
  }
  const base = {
    ...sourceProduct || {},
    id: resolvedId,
    product_id: resolvedId,
    extension_type: (sourceProduct == null ? void 0 : sourceProduct.extension_type) ?? ((_e = booking == null ? void 0 : booking.product) == null ? void 0 : _e.extension_type) ?? (sourceProduct == null ? void 0 : sourceProduct.extension_type),
    title: productTitle || (sourceProduct == null ? void 0 : sourceProduct.title) || ((_f = booking == null ? void 0 : booking.product) == null ? void 0 : _f.title),
    price: (sourceProduct == null ? void 0 : sourceProduct.price) ?? selling,
    selling_price: product.selling_price,
    original_price: product.original_price,
    ...productOptionString ? { product_option_string: productOptionString } : {},
    _extend: extend,
    new: 0,
    autoClose: false,
    order_detail_id: product.order_detail_id ?? null,
    booking_id: booking.id ?? booking.booking_id ?? 0
  };
  if ((sourceProduct == null ? void 0 : sourceProduct.capacity) !== void 0) {
    base.capacity = sourceProduct.capacity;
  }
  const topLevelDuration = resolveTopLevelDuration(booking, sourceProduct);
  if (topLevelDuration !== void 0) {
    base.duration = topLevelDuration;
  }
  if ((sourceProduct == null ? void 0 : sourceProduct.product_resource) !== void 0) {
    base.product_resource = sourceProduct.product_resource;
  } else {
    const synthesized = synthesizeProductResourceFromBooking(booking);
    if (synthesized) {
      base.product_resource = synthesized;
    }
  }
  if (Array.isArray(sourceProduct == null ? void 0 : sourceProduct.schedules) && sourceProduct.schedules.length) {
    base.schedules = sourceProduct.schedules;
  }
  if (Array.isArray(sourceProduct == null ? void 0 : sourceProduct["schedule.ids"]) && sourceProduct["schedule.ids"].length) {
    base["schedule.ids"] = sourceProduct["schedule.ids"];
  }
  if (booking.schedule_event_id !== void 0) {
    base.schedule_event_id = booking.schedule_event_id;
  }
  return base;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  buildCacheItemFromOrderLine
});
