import { CustomerUser } from "@open-mercato/core/modules/customer_accounts/data/entities";
import { lookupHashCandidates } from "@open-mercato/shared/lib/encryption/aes";
import { 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-reverse" });
const metadata = {
  event: "customers.person.created",
  persistent: true,
  id: "customer_accounts:auto-link-crm-reverse"
};
async function handle(payload, ctx) {
  const data = payload;
  const eventId = data?.id;
  const tenantId = data?.tenantId;
  const organizationId = data?.organizationId;
  if (!eventId || !tenantId) return;
  const em = ctx.resolve("em");
  try {
    const { CustomerEntity } = await import("@open-mercato/core/modules/customers/data/entities");
    let entity = await findOneWithDecryption(
      em,
      CustomerEntity,
      { id: eventId, tenantId, kind: "person", deletedAt: null },
      void 0,
      { tenantId, organizationId }
    );
    if (!entity) {
      const { CustomerPersonProfile: CustomerPersonProfile2 } = await import("@open-mercato/core/modules/customers/data/entities");
      const profile = await em.findOne(CustomerPersonProfile2, { id: eventId }, { populate: ["entity"] });
      if (profile?.entity) {
        entity = await findOneWithDecryption(
          em,
          CustomerEntity,
          { id: profile.entity.id ?? profile.entity, tenantId, deletedAt: null },
          void 0,
          { tenantId, organizationId }
        );
      }
    }
    if (!entity) return;
    const email = entity.primaryEmail;
    if (!email) return;
    const emailHashes = lookupHashCandidates(email.toLowerCase().trim());
    const { CustomerPersonProfile } = await import("@open-mercato/core/modules/customers/data/entities");
    const personProfile = await em.findOne(CustomerPersonProfile, { entity: entity.id });
    const companyEntityId = personProfile?.companyEntityId;
    const customerUser = await em.findOne(CustomerUser, {
      emailHash: { $in: emailHashes },
      tenantId,
      deletedAt: null,
      personEntityId: null
    });
    if (customerUser) {
      const updates = { personEntityId: entity.id };
      if (companyEntityId && !customerUser.customerEntityId) {
        updates.customerEntityId = companyEntityId;
      }
      const affected = await em.nativeUpdate(CustomerUser, { id: customerUser.id, personEntityId: null }, updates);
      if (affected === 0) return;
    }
  } catch (err) {
    logger.error("Failed to link CRM person to customer user", { err });
  }
}
export {
  handle as default,
  metadata
};
//# sourceMappingURL=autoLinkCrmReverse.js.map
