import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
async function enrichOrderPayload(payload, ctx) {
  const enriched = { ...payload };
  const warnings = [];
  if (ctx.salesChannelClass) {
    try {
      const channelWhere = {
        tenantId: ctx.scope.tenantId,
        organizationId: ctx.scope.organizationId,
        deletedAt: null
      };
      if (enriched.channelId) {
        channelWhere.id = enriched.channelId;
      }
      const channel = await findOneWithDecryption(
        ctx.em,
        ctx.salesChannelClass,
        channelWhere,
        enriched.channelId ? void 0 : { orderBy: { name: "ASC" } },
        ctx.scope
      );
      if (channel) {
        if (!enriched.channelId) enriched.channelId = channel.id;
        if (!enriched.currencyCode && channel.currencyCode) {
          enriched.currencyCode = channel.currencyCode;
        }
      } else {
        warnings.push("no_channel_resolved");
      }
    } catch {
      warnings.push("no_channel_resolved");
    }
  } else if (!enriched.channelId) {
    warnings.push("no_channel_resolved");
  }
  if (!enriched.customerEntityId) {
    const senderMatch = ctx.contactMatches.find(
      (m) => m.participant.email.toLowerCase() === ctx.senderEmail.toLowerCase() && m.match?.contactId
    );
    if (senderMatch?.match) {
      enriched.customerEntityId = senderMatch.match.contactId;
    }
  }
  const customerEntityId = typeof enriched.customerEntityId === "string" ? enriched.customerEntityId : null;
  if (customerEntityId && !enriched.billingAddress && !enriched.billingAddressId && ctx.customerAddressClass) {
    try {
      const primaryAddress = await findOneWithDecryption(
        ctx.em,
        ctx.customerAddressClass,
        {
          entity: customerEntityId,
          tenantId: ctx.scope.tenantId,
          organizationId: ctx.scope.organizationId
        },
        { orderBy: { isPrimary: "DESC", createdAt: "DESC" } },
        ctx.scope
      );
      if (primaryAddress) {
        enriched.billingAddressId = primaryAddress.id;
        if (!enriched.shippingAddress && !enriched.shippingAddressId) {
          enriched.shippingAddressId = primaryAddress.id;
        }
      }
    } catch {
    }
  }
  const lineItems = Array.isArray(enriched.lineItems) ? enriched.lineItems : [];
  const catalogProductIds = new Set(ctx.catalogProducts.map((p) => p.id));
  if (lineItems.length > 0) {
    for (const item of lineItems) {
      if (item.productId && typeof item.productId === "string" && !catalogProductIds.has(item.productId)) {
        item.productId = void 0;
      }
      if (item.productId) continue;
      const productName = typeof item.productName === "string" ? item.productName.toLowerCase().trim() : "";
      if (!productName || ctx.catalogProducts.length === 0) continue;
      const match = ctx.catalogProducts.find((p) => {
        const catalogName = p.name.toLowerCase().trim();
        const catalogSku = (p.sku || "").toLowerCase().trim();
        return catalogName === productName || catalogSku === productName || catalogName.includes(productName) || productName.includes(catalogName);
      });
      if (match) {
        item.productId = match.id;
        if (match.sku) item.sku = match.sku;
        if (match.price && !item.unitPrice) item.catalogPrice = match.price;
      }
    }
  }
  for (const item of lineItems) {
    if (typeof item.quantity === "number") {
      item.quantity = String(item.quantity);
    }
    if (typeof item.unitPrice === "number") {
      item.unitPrice = String(item.unitPrice);
    }
  }
  if (!enriched.currencyCode) {
    warnings.push("no_currency_resolved");
  }
  return { payload: enriched, warnings };
}
export {
  enrichOrderPayload
};
//# sourceMappingURL=payloadEnrichment.js.map
