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_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 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, fallbackFetcher) {
  if (!(choices == null ? void 0 : choices.length)) return [];
  const productMap = /* @__PURE__ */ new Map();
  applyChoiceSnapshots(choices, productMap);
  let missingIds = collectMissingProductIds(choices, productMap);
  if (missingIds.length && fallbackFetcher) {
    try {
      const fallback = await 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);
    }
  }
  return choices.map(
    (choice) => buildGiftOrderProduct(choice, productMap.get(Number(choice.product_id)) || {}, ctx)
  );
}
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
});
