import { loadCustomFieldValues } from "@open-mercato/shared/lib/crud/custom-fields";
import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
import { CustomerActivity, CustomerInteraction } from "../data/entities.js";
import { CUSTOMER_INTERACTION_ACTIVITY_ADAPTER_SOURCE } from "./interactionCompatibility.js";
async function loadLegacyActivityCustomValues(em, activity) {
  const values = await loadCustomFieldValues({
    em,
    entityId: "customers:customer_activity",
    recordIds: [activity.id],
    tenantIdByRecord: { [activity.id]: activity.tenantId },
    organizationIdByRecord: { [activity.id]: activity.organizationId },
    tenantFallbacks: [activity.tenantId]
  });
  return values[activity.id] ?? null;
}
async function ensureCanonicalActivityBridge(em, commandBus, commandContext, activity) {
  const existing = await em.findOne(CustomerInteraction, { id: activity.id, tenantId: activity.tenantId });
  if (existing) return existing.id;
  const entityId = typeof activity.entity === "string" ? activity.entity : activity.entity.id;
  const dealId = activity.deal ? typeof activity.deal === "string" ? activity.deal : activity.deal.id : null;
  const customValues = await loadLegacyActivityCustomValues(em, activity);
  await commandBus.execute("customers.interactions.create", {
    input: {
      id: activity.id,
      tenantId: activity.tenantId,
      organizationId: activity.organizationId,
      entityId,
      interactionType: activity.activityType,
      title: activity.subject ?? null,
      body: activity.body ?? null,
      occurredAt: activity.occurredAt ?? null,
      status: activity.occurredAt ? "done" : "planned",
      dealId,
      authorUserId: activity.authorUserId ?? null,
      appearanceIcon: activity.appearanceIcon ?? null,
      appearanceColor: activity.appearanceColor ?? null,
      source: CUSTOMER_INTERACTION_ACTIVITY_ADAPTER_SOURCE,
      ...customValues ? { customValues } : {}
    },
    ctx: commandContext
  });
  return activity.id;
}
async function resolveCanonicalActivityTargetId(em, commandBus, commandContext, targetId, tenantId) {
  const existing = await em.findOne(CustomerInteraction, { id: targetId, tenantId });
  if (existing) return existing.id;
  const legacy = await findOneWithDecryption(
    em,
    CustomerActivity,
    { id: targetId, tenantId },
    { populate: ["entity", "deal"] },
    { tenantId }
  );
  if (!legacy) return targetId;
  return ensureCanonicalActivityBridge(em, commandBus, commandContext, legacy);
}
export {
  ensureCanonicalActivityBridge,
  resolveCanonicalActivityTargetId
};
//# sourceMappingURL=legacyActivityBridge.js.map
