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/salesSdk/giftSelect/buildGiftOrderProducts.ts
var buildGiftOrderProducts_exports = {};
__export(buildGiftOrderProducts_exports, {
  buildGiftOrderProduct: () => buildGiftOrderProduct,
  buildGiftOrderProductsFromChoices: () => buildGiftOrderProductsFromChoices,
  fetchGiftProductMap: () => fetchGiftProductMap,
  prefetchGiftProductQueryCache: () => prefetchGiftProductQueryCache,
  seedGiftProductQueryCache: () => seedGiftProductQueryCache
});
module.exports = __toCommonJS(buildGiftOrderProducts_exports);
var import_server = require("../../../components/shoppingCart/server");
var import_utils = require("../../../components/booking/info/service2/utils");
var import_resolveLocalizedText = require("../utils/resolveLocalizedText");
function createUuidV4() {
  const template = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
  return template.replace(/[xy]/g, (char) => {
    const r = Math.floor(Math.random() * 16);
    const v = char === "x" ? r : r & 3 | 8;
    return v.toString(16);
  });
}
var giftProductByIdCache = /* @__PURE__ */ new Map();
function resolveProductId(product) {
  const id = Number((product == null ? void 0 : product.id) ?? (product == null ? void 0 : product.product_id));
  return Number.isFinite(id) && id > 0 ? id : null;
}
function seedGiftProductQueryCache(products) {
  if (!Array.isArray(products) || !products.length) return;
  products.forEach((product) => {
    const id = resolveProductId(product);
    if (id) {
      giftProductByIdCache.set(id, product);
    }
  });
}
function resolveGiftCatalogPrice(productData) {
  return Number(
    (productData == null ? void 0 : productData._initPrice) ?? (productData == null ? void 0 : productData.origin_price) ?? (productData == null ? void 0 : productData.original_price) ?? (productData == null ? void 0 : productData.price) ?? 0
  ) || 0;
}
function buildGiftOrderProduct(choice, productData, ctx) {
  var _a;
  const uid = createUuidV4();
  const catalogPrice = resolveGiftCatalogPrice(productData || {});
  const variant = Array.isArray(productData == null ? void 0 : productData.variants) ? productData.variants.find(
    (v) => Number(v == null ? void 0 : v.id) === Number(choice.product_variant_id)
  ) : null;
  const variantPrice = variant ? Number((variant == null ? void 0 : variant.price) ?? (variant == null ? void 0 : variant.selling_price) ?? catalogPrice) || 0 : catalogPrice;
  const finalOriginal = variantPrice.toFixed(2);
  const productTitle = (productData == null ? void 0 : productData.title) || (productData == null ? void 0 : productData.name) || (productData == null ? void 0 : productData.product_title) || "";
  return {
    product_id: choice.product_id,
    product_variant_id: choice.product_variant_id,
    order_detail_id: null,
    num: choice.quantity,
    selling_price: "0.00",
    original_price: finalOriginal,
    tax_fee: "0.00",
    is_charge_tax: 0,
    discount_list: [
      {
        type: "promotion",
        amount: finalOriginal,
        discount: {
          original_amount: finalOriginal,
          fixed_amount: finalOriginal,
          title: (0, import_resolveLocalizedText.resolveLocalizedText)(ctx.strategyName) || "",
          resource_id: ""
        }
      }
    ],
    product_option_item: [],
    product_bundle: [],
    metadata: {
      unique_identification_number: uid,
      source_product_price: "0.00",
      main_product_original_price: finalOriginal,
      main_product_selling_price: "0.00",
      price_schema_version: 2,
      product_name: productTitle,
      _giftInfo: {
        strategyId: ctx.strategyId,
        strategyName: ctx.strategyName,
        sourceProductIds: ctx.sourceProductIds,
        sourceProductId: (_a = ctx.sourceProductIds) == null ? void 0 : _a[0],
        lastEvaluatedGiftCount: ctx.giftCount
      }
    }
  };
}
function isBookingGiftCacheItem(cacheItem) {
  if (!(cacheItem == null ? void 0 : cacheItem._extend)) return false;
  return !(0, import_utils.isNormalProductByDurationSchedule)(cacheItem);
}
function applyGiftMetadataToOrderProduct(orderLine, choice, productData, ctx) {
  var _a, _b;
  const catalogPrice = resolveGiftCatalogPrice({
    ...productData,
    original_price: (orderLine == null ? void 0 : orderLine.original_price) ?? (productData == null ? void 0 : productData.original_price),
    price: (orderLine == null ? void 0 : orderLine.selling_price) ?? (productData == null ? void 0 : productData.price)
  });
  const finalOriginal = catalogPrice.toFixed(2);
  const productTitle = (productData == null ? void 0 : productData.title) || (productData == null ? void 0 : productData.name) || (productData == null ? void 0 : productData.product_title) || ((_a = orderLine == null ? void 0 : orderLine.metadata) == null ? void 0 : _a.product_name) || "";
  const metadata = orderLine.metadata || {};
  return {
    ...orderLine,
    product_id: choice.product_id,
    product_variant_id: choice.product_variant_id,
    num: Number(orderLine.num ?? choice.quantity ?? 1) || 1,
    selling_price: "0.00",
    original_price: finalOriginal,
    tax_fee: "0.00",
    is_charge_tax: 0,
    discount_list: [
      {
        type: "promotion",
        amount: finalOriginal,
        discount: {
          original_amount: finalOriginal,
          fixed_amount: finalOriginal,
          title: (0, import_resolveLocalizedText.resolveLocalizedText)(ctx.strategyName) || "",
          resource_id: ""
        }
      }
    ],
    metadata: {
      ...metadata,
      unique_identification_number: metadata.unique_identification_number || orderLine.unique_identification_number || createUuidV4(),
      source_product_price: "0.00",
      main_product_original_price: finalOriginal,
      main_product_selling_price: "0.00",
      price_schema_version: 2,
      product_name: productTitle,
      _giftInfo: {
        strategyId: ctx.strategyId,
        strategyName: ctx.strategyName,
        sourceProductIds: ctx.sourceProductIds,
        sourceProductId: (_b = ctx.sourceProductIds) == null ? void 0 : _b[0],
        lastEvaluatedGiftCount: ctx.giftCount
      }
    }
  };
}
function linkGiftProductAndBooking(product, booking) {
  const productMetadata = product.metadata || {};
  const bookingMetadata = booking.metadata && typeof booking.metadata === "object" ? { ...booking.metadata } : {};
  const productUid = String(
    productMetadata.unique_identification_number || product.unique_identification_number || createUuidV4()
  );
  const bookingUid = String(bookingMetadata.unique_identification_number || createUuidV4());
  productMetadata.unique_identification_number = productUid;
  bookingMetadata.unique_identification_number = bookingUid;
  if (booking.holder !== void 0) {
    bookingMetadata.holder = booking.holder;
  }
  return {
    product: {
      ...product,
      unique_identification_number: productUid,
      booking_uid: bookingUid,
      metadata: {
        ...productMetadata,
        booking_uid: bookingUid
      }
    },
    booking: {
      ...booking,
      product_uid: productUid,
      metadata: bookingMetadata
    }
  };
}
function buildBookingGiftOrderProduct(choice, cacheItem, ctx, bookingTicket) {
  if (typeof (bookingTicket == null ? void 0 : bookingTicket.transformDetailToProductAndBooking) !== "function") {
    return null;
  }
  try {
    const quantity = Math.max(1, Number(choice.quantity) || 1);
    const products = [];
    const bookings = [];
    for (let index = 0; index < quantity; index += 1) {
      const cacheItemForOne = {
        ...cacheItem,
        _extend: {
          ...cacheItem._extend || {},
          quantity: 1
        }
      };
      const transformed = bookingTicket.transformDetailToProductAndBooking({
        item: cacheItem,
        cacheItem: cacheItemForOne,
        options: { quantity: 1 }
      });
      if (!transformed.booking) {
        return null;
      }
      const giftProduct = applyGiftMetadataToOrderProduct(
        {
          ...transformed.product,
          num: 1
        },
        {
          ...choice,
          quantity: 1
        },
        transformed.cacheItem || cacheItem,
        ctx
      );
      const linked = linkGiftProductAndBooking(giftProduct, transformed.booking);
      products.push(linked.product);
      bookings.push(linked.booking);
    }
    return { products, bookings };
  } catch (error) {
    console.warn("[SalesSdk/giftSelect] build booking gift failed", error);
    return null;
  }
}
function applyChoiceSnapshots(choices, productMap) {
  choices.forEach((choice) => {
    const productId = Number(choice.product_id);
    if (!productId || productMap.has(productId) || !choice._productSnapshot) return;
    productMap.set(productId, choice._productSnapshot);
  });
}
function collectMissingProductIds(choices, productMap) {
  return Array.from(
    new Set(
      choices.map((c) => Number(c.product_id)).filter((id) => Number.isFinite(id) && id > 0 && !productMap.has(id))
    )
  );
}
async function fetchGiftProductMap(productIds) {
  const ids = Array.from(new Set(productIds.filter((id) => Number.isFinite(id) && id > 0)));
  if (!ids.length) return /* @__PURE__ */ new Map();
  const map = /* @__PURE__ */ new Map();
  const missingIds = [];
  ids.forEach((id) => {
    const cached = giftProductByIdCache.get(id);
    if (cached) {
      map.set(id, cached);
    } else {
      missingIds.push(id);
    }
  });
  if (!missingIds.length) {
    return map;
  }
  const products = await (0, import_server.getProducts)({ ids: missingIds, isGift: true }) || [];
  products.forEach((p) => {
    const id = resolveProductId(p);
    if (!id) return;
    giftProductByIdCache.set(id, p);
    map.set(id, p);
  });
  return map;
}
async function buildGiftOrderProductsFromChoices(choices, ctx, options) {
  if (!(choices == null ? void 0 : choices.length)) return { products: [], bookings: [] };
  const productMap = /* @__PURE__ */ new Map();
  applyChoiceSnapshots(choices, productMap);
  let missingIds = collectMissingProductIds(choices, productMap);
  if (missingIds.length && (options == null ? void 0 : options.fallbackFetcher)) {
    try {
      const fallback = await options.fallbackFetcher(missingIds) || [];
      fallback.forEach((p) => {
        const id = resolveProductId(p);
        if (id) productMap.set(id, p);
      });
    } catch (error) {
      console.warn("[SalesSdk/giftSelect] fallback getProductByIds failed", error);
    }
  }
  missingIds = collectMissingProductIds(choices, productMap);
  if (missingIds.length) {
    try {
      const fromNetwork = await fetchGiftProductMap(missingIds);
      fromNetwork.forEach((product, id) => {
        if (!productMap.has(id)) {
          productMap.set(id, product);
        }
      });
    } catch (error) {
      console.warn("[SalesSdk/giftSelect] getProducts failed", error);
    }
  }
  const result = { products: [], bookings: [] };
  choices.forEach((choice) => {
    var _a;
    const productData = productMap.get(Number(choice.product_id)) || {};
    const snapshot = choice._productSnapshot;
    if (isBookingGiftCacheItem(snapshot)) {
      const bookingGift = buildBookingGiftOrderProduct(
        choice,
        snapshot,
        ctx,
        options == null ? void 0 : options.bookingTicket
      );
      if (bookingGift == null ? void 0 : bookingGift.products.length) {
        result.products.push(...bookingGift.products);
        (_a = result.bookings) == null ? void 0 : _a.push(...bookingGift.bookings || []);
        return;
      }
    }
    result.products.push(buildGiftOrderProduct(choice, productData, ctx));
  });
  return result;
}
async function prefetchGiftProductQueryCache(productIds) {
  const ids = Array.from(new Set(productIds.filter((id) => Number.isFinite(id) && id > 0)));
  const missing = ids.filter((id) => !giftProductByIdCache.has(id));
  if (!missing.length) return;
  await fetchGiftProductMap(missing);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  buildGiftOrderProduct,
  buildGiftOrderProductsFromChoices,
  fetchGiftProductMap,
  prefetchGiftProductQueryCache,
  seedGiftProductQueryCache
});
