import { findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("inbox_ops").child({ component: "catalog-lookup" });
const MAX_CATALOG_PRODUCTS = 50;
async function fetchCatalogProductsForExtraction(em, scope, deps) {
  if (!deps?.catalogProductClass || !deps?.catalogProductPriceClass) return [];
  try {
    const products = await findWithDecryption(
      em,
      deps.catalogProductClass,
      {
        organizationId: scope.organizationId,
        tenantId: scope.tenantId,
        deletedAt: null
      },
      { limit: MAX_CATALOG_PRODUCTS, orderBy: { updatedAt: "DESC" } },
      { tenantId: scope.tenantId, organizationId: scope.organizationId }
    );
    if (!products || products.length === 0) return [];
    const productIds = products.map((p) => p.id);
    const prices = await findWithDecryption(
      em,
      deps.catalogProductPriceClass,
      {
        product: { $in: productIds },
        organizationId: scope.organizationId,
        tenantId: scope.tenantId
      },
      { orderBy: { createdAt: "DESC" } },
      { tenantId: scope.tenantId, organizationId: scope.organizationId }
    );
    const priceByProduct = /* @__PURE__ */ new Map();
    for (const price of prices) {
      const rawProduct = price.product;
      const productId = typeof rawProduct === "string" ? rawProduct : rawProduct && typeof rawProduct === "object" && "id" in rawProduct ? String(rawProduct.id) : void 0;
      if (productId && !priceByProduct.has(productId)) {
        const amount = price.unitPriceNet ?? price.unitPriceGross ?? null;
        if (amount) priceByProduct.set(productId, amount);
      }
    }
    return products.map((product) => ({
      id: product.id,
      name: product.title,
      sku: product.sku ?? void 0,
      price: priceByProduct.get(product.id)
    }));
  } catch (err) {
    logger.error("Failed to fetch catalog products", { err });
    return [];
  }
}
export {
  fetchCatalogProductsForExtraction
};
//# sourceMappingURL=catalogLookup.js.map
