import { CustomerUser } from "@open-mercato/core/modules/customer_accounts/data/entities";
import { findWithDecryption, findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("customer_accounts").child({ component: "auto-link-crm" });
const metadata = {
  event: "customer_accounts.user.created",
  persistent: true,
  id: "customer_accounts:auto-link-crm"
};
async function handle(payload, ctx) {
  const data = payload;
  const userId = data?.id;
  const tenantId = data?.tenantId;
  const organizationId = data?.organizationId;
  if (!userId || !tenantId) return;
  const em = ctx.resolve("em");
  try {
    const user = await findOneWithDecryption(em, CustomerUser, { id: userId, tenantId, deletedAt: null }, void 0, { tenantId, organizationId });
    if (!user) return;
    if (user.personEntityId) return;
    const email = (data?.email ? data.email : user.email)?.toLowerCase().trim();
    if (!email) return;
    const { CustomerEntity } = await import("@open-mercato/core/modules/customers/data/entities");
    const personEntities = await findWithDecryption(
      em,
      CustomerEntity,
      { tenantId, kind: "person", deletedAt: null },
      { limit: 500 },
      { tenantId, organizationId }
    );
    const matchingEntity = personEntities.find(
      (e) => e.primaryEmail && e.primaryEmail.toLowerCase().trim() === email
    );
    if (!matchingEntity) return;
    const { CustomerPersonProfile } = await import("@open-mercato/core/modules/customers/data/entities");
    const profile = await em.findOne(CustomerPersonProfile, { entity: matchingEntity.id });
    const companyEntityId = profile?.companyEntityId;
    const updates = { personEntityId: matchingEntity.id };
    if (companyEntityId) {
      updates.customerEntityId = companyEntityId;
    }
    await em.nativeUpdate(CustomerUser, { id: userId }, updates);
  } catch (err) {
    logger.error("Failed to link customer user to CRM person", { err });
  }
}
export {
  handle as default,
  metadata
};
//# sourceMappingURL=autoLinkCrm.js.map
