import { registerCommand } from "@open-mercato/shared/lib/commands";
import {
  parseWithCustomFields,
  setCustomFieldsIfAny,
  emitCrudSideEffects,
  emitCrudUndoSideEffects,
  requireId,
  snapshotsEqual
} from "@open-mercato/shared/lib/commands/helpers";
import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
import {
  CustomerAddress,
  CustomerComment,
  CustomerCompanyProfile,
  CustomerDeal,
  CustomerDealCompanyLink,
  CustomerActivity,
  CustomerInteraction,
  CustomerTodoLink,
  CustomerEntity,
  CustomerPersonCompanyLink,
  CustomerPersonProfile,
  CustomerTagAssignment
} from "../data/entities.js";
import {
  companyCreateSchema,
  companyUpdateSchema
} from "../data/validators.js";
import {
  ensureOrganizationScope,
  ensureTenantScope,
  extractUndoPayload,
  assertFound,
  syncEntityTags,
  loadEntityTagIds,
  emitQueryIndexDeleteEvents,
  emitQueryIndexUpsertEvents
} from "./shared.js";
import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
import {
  loadCustomFieldSnapshot,
  buildCustomFieldResetMap
} from "@open-mercato/shared/lib/commands/customFieldSnapshots";
import { E } from "../../../generated/entities.ids.generated.js";
import { findOneWithDecryption, findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
import { CUSTOMER_ENTITY_ID, resolveCompanyCustomFieldRouting } from "../lib/customFieldRouting.js";
import { CustomFieldValue } from "@open-mercato/core/modules/entities/data/entities";
import { withAtomicFlush } from "@open-mercato/shared/lib/commands/flush";
import { resolveRedoSnapshot } from "@open-mercato/shared/lib/commands/redo";
const COMPANY_ENTITY_ID = "customers:customer_company_profile";
const INTERACTION_ENTITY_ID = "customers:customer_interaction";
const companyCrudIndexer = {
  entityType: E.customers.customer_company_profile
};
const companyCrudEvents = {
  module: "customers",
  entity: "company",
  persistent: true,
  buildPayload: (ctx) => ({
    id: ctx.identifiers.id,
    entityId: ctx.entity?.id ?? ctx.identifiers.id,
    organizationId: ctx.identifiers.organizationId,
    tenantId: ctx.identifiers.tenantId
  })
};
function buildCompanyHasDependentsError(translate, counts) {
  const blockers = [];
  if (counts.personLinks > 0) {
    blockers.push(
      translate("customers.companies.delete.blockers.persons", "linked persons ({{count}})", { count: counts.personLinks })
    );
  }
  if (counts.dealLinks > 0) {
    blockers.push(
      translate("customers.companies.delete.blockers.deals", "linked deals ({{count}})", { count: counts.dealLinks })
    );
  }
  if (counts.directPeople > 0) {
    blockers.push(
      translate("customers.companies.delete.blockers.directPeople", "persons whose primary company is this one ({{count}})", { count: counts.directPeople })
    );
  }
  const summary = blockers.join(", ");
  const message = translate(
    "customers.companies.delete.blocked",
    "Cannot delete company: {{blockers}}. Please unlink or reassign first.",
    { blockers: summary }
  );
  return new CrudHttpError(422, { error: message, code: "COMPANY_HAS_DEPENDENTS" });
}
function companyEntityIndexEntry(entity) {
  return {
    entityType: E.customers.customer_entity,
    recordId: entity.id,
    tenantId: entity.tenantId,
    organizationId: entity.organizationId
  };
}
async function loadCompanySnapshot(em, id) {
  const entity = await em.findOne(CustomerEntity, { id, deletedAt: null });
  if (!entity || entity.kind !== "company") return null;
  const profile = await em.findOne(CustomerCompanyProfile, { entity });
  if (!profile) return null;
  const tagIds = await loadEntityTagIds(em, entity);
  const deals = await findWithDecryption(
    em,
    CustomerDealCompanyLink,
    { company: entity },
    { orderBy: { createdAt: "asc" }, populate: ["deal"] },
    { tenantId: entity.tenantId, organizationId: entity.organizationId }
  );
  const members = await findWithDecryption(
    em,
    CustomerPersonProfile,
    { company: entity },
    { orderBy: { createdAt: "asc" }, populate: ["entity"] },
    { tenantId: entity.tenantId, organizationId: entity.organizationId }
  );
  const addresses = await em.find(CustomerAddress, { entity }, { orderBy: { createdAt: "asc" } });
  const comments = await findWithDecryption(
    em,
    CustomerComment,
    { entity },
    { orderBy: { createdAt: "asc" }, populate: ["deal"] },
    { tenantId: entity.tenantId, organizationId: entity.organizationId }
  );
  const activities = await findWithDecryption(
    em,
    CustomerActivity,
    { entity },
    { orderBy: { createdAt: "asc" }, populate: ["deal"] },
    { tenantId: entity.tenantId, organizationId: entity.organizationId }
  );
  const todoLinks = await em.find(CustomerTodoLink, { entity }, { orderBy: { createdAt: "asc" } });
  const interactions = await em.find(CustomerInteraction, { entity }, { orderBy: { createdAt: "asc" } });
  const custom = await loadCustomFieldSnapshot(em, {
    entityId: COMPANY_ENTITY_ID,
    recordId: profile.id,
    tenantId: entity.tenantId,
    organizationId: entity.organizationId
  });
  return {
    entity: {
      id: entity.id,
      organizationId: entity.organizationId,
      tenantId: entity.tenantId,
      displayName: entity.displayName,
      description: entity.description ?? null,
      ownerUserId: entity.ownerUserId ?? null,
      primaryEmail: entity.primaryEmail ?? null,
      primaryPhone: entity.primaryPhone ?? null,
      status: entity.status ?? null,
      lifecycleStage: entity.lifecycleStage ?? null,
      source: entity.source ?? null,
      temperature: entity.temperature ?? null,
      renewalQuarter: entity.renewalQuarter ?? null,
      nextInteractionAt: entity.nextInteractionAt ?? null,
      nextInteractionName: entity.nextInteractionName ?? null,
      nextInteractionRefId: entity.nextInteractionRefId ?? null,
      nextInteractionIcon: entity.nextInteractionIcon ?? null,
      nextInteractionColor: entity.nextInteractionColor ?? null,
      isActive: entity.isActive
    },
    profile: {
      id: profile.id,
      legalName: profile.legalName ?? null,
      brandName: profile.brandName ?? null,
      domain: profile.domain ?? null,
      websiteUrl: profile.websiteUrl ?? null,
      industry: profile.industry ?? null,
      sizeBucket: profile.sizeBucket ?? null,
      annualRevenue: profile.annualRevenue ?? null
    },
    tagIds,
    custom,
    deals: deals.filter((link) => link.deal).map((link) => ({
      id: link.id,
      dealId: link.deal.id,
      createdAt: link.createdAt
    })),
    members: members.filter((member) => member.entity).map((member) => ({
      profileId: member.id,
      personEntityId: typeof member.entity === "string" ? member.entity : member.entity.id
    })),
    addresses: addresses.map((address) => ({
      id: address.id,
      name: address.name ?? null,
      purpose: address.purpose ?? null,
      addressLine1: address.addressLine1,
      addressLine2: address.addressLine2 ?? null,
      city: address.city ?? null,
      region: address.region ?? null,
      postalCode: address.postalCode ?? null,
      country: address.country ?? null,
      latitude: address.latitude ?? null,
      longitude: address.longitude ?? null,
      isPrimary: address.isPrimary
    })),
    comments: comments.map((comment) => ({
      id: comment.id,
      body: comment.body,
      authorUserId: comment.authorUserId ?? null,
      dealId: comment.deal ? typeof comment.deal === "string" ? comment.deal : comment.deal.id : null,
      createdAt: comment.createdAt,
      updatedAt: comment.updatedAt,
      deletedAt: comment.deletedAt ?? null,
      appearanceIcon: comment.appearanceIcon ?? null,
      appearanceColor: comment.appearanceColor ?? null
    })),
    activities: activities.map((activity) => ({
      id: activity.id,
      activityType: activity.activityType,
      subject: activity.subject ?? null,
      body: activity.body ?? null,
      occurredAt: activity.occurredAt ?? null,
      authorUserId: activity.authorUserId ?? null,
      appearanceIcon: activity.appearanceIcon ?? null,
      appearanceColor: activity.appearanceColor ?? null,
      dealId: activity.deal ? typeof activity.deal === "string" ? activity.deal : activity.deal.id : null,
      createdAt: activity.createdAt,
      updatedAt: activity.updatedAt
    })),
    todos: todoLinks.map((todo) => ({
      id: todo.id,
      todoId: todo.todoId,
      todoSource: todo.todoSource,
      createdAt: todo.createdAt,
      createdByUserId: todo.createdByUserId ?? null
    })),
    interactions: await Promise.all(
      interactions.map(async (interaction) => ({
        id: interaction.id,
        interactionType: interaction.interactionType,
        title: interaction.title ?? null,
        body: interaction.body ?? null,
        status: interaction.status,
        scheduledAt: interaction.scheduledAt ?? null,
        occurredAt: interaction.occurredAt ?? null,
        priority: interaction.priority ?? null,
        authorUserId: interaction.authorUserId ?? null,
        ownerUserId: interaction.ownerUserId ?? null,
        appearanceIcon: interaction.appearanceIcon ?? null,
        appearanceColor: interaction.appearanceColor ?? null,
        source: interaction.source ?? null,
        dealId: interaction.dealId ?? null,
        createdAt: interaction.createdAt,
        updatedAt: interaction.updatedAt,
        deletedAt: interaction.deletedAt ?? null,
        custom: await loadCustomFieldSnapshot(em, {
          entityId: INTERACTION_ENTITY_ID,
          recordId: interaction.id,
          tenantId: entity.tenantId,
          organizationId: entity.organizationId
        })
      }))
    )
  };
}
async function setCompanyCustomFields(ctx, entityId, profileId, organizationId, tenantId, values) {
  if (!values || !Object.keys(values).length) return;
  const em = ctx.container.resolve("em");
  const routing = await resolveCompanyCustomFieldRouting(em, tenantId, organizationId);
  const entityScoped = {};
  const profileScoped = {};
  for (const [key, value] of Object.entries(values)) {
    const target = routing.get(key) ?? COMPANY_ENTITY_ID;
    if (target === CUSTOMER_ENTITY_ID) entityScoped[key] = value;
    else profileScoped[key] = value;
  }
  const de = ctx.container.resolve("dataEngine");
  if (Object.keys(entityScoped).length) {
    await setCustomFieldsIfAny({
      dataEngine: de,
      entityId: CUSTOMER_ENTITY_ID,
      recordId: entityId,
      organizationId,
      tenantId,
      values: entityScoped,
      notify: false
    });
  }
  if (Object.keys(profileScoped).length) {
    await setCustomFieldsIfAny({
      dataEngine: de,
      entityId: COMPANY_ENTITY_ID,
      recordId: profileId,
      organizationId,
      tenantId,
      values: profileScoped,
      notify: false
    });
  }
}
function normalizeOptionalString(value) {
  if (typeof value !== "string") return null;
  const trimmed = value.trim();
  return trimmed.length ? trimmed : null;
}
function normalizeHexColor(value) {
  if (typeof value !== "string") return null;
  const trimmed = value.trim().toLowerCase();
  return /^#([0-9a-f]{6})$/.test(trimmed) ? trimmed : null;
}
const createCompanyCommand = {
  id: "customers.companies.create",
  async execute(rawInput, ctx) {
    const { parsed, custom } = parseWithCustomFields(companyCreateSchema, rawInput);
    ensureTenantScope(ctx, parsed.tenantId);
    ensureOrganizationScope(ctx, parsed.organizationId);
    const em = ctx.container.resolve("em").fork();
    const nextInteractionName = parsed.nextInteraction?.name ? parsed.nextInteraction.name.trim() : null;
    const nextInteractionRefId = normalizeOptionalString(parsed.nextInteraction?.refId);
    const nextInteractionIcon = normalizeOptionalString(parsed.nextInteraction?.icon);
    const nextInteractionColor = normalizeHexColor(parsed.nextInteraction?.color);
    const primaryPhone = normalizeOptionalString(parsed.primaryPhone);
    const entity = em.create(CustomerEntity, {
      organizationId: parsed.organizationId,
      tenantId: parsed.tenantId,
      kind: "company",
      displayName: parsed.displayName,
      description: parsed.description ?? null,
      ownerUserId: parsed.ownerUserId ?? null,
      primaryEmail: parsed.primaryEmail ?? null,
      primaryPhone,
      status: parsed.status ?? null,
      lifecycleStage: parsed.lifecycleStage ?? null,
      source: parsed.source ?? null,
      nextInteractionAt: parsed.nextInteraction?.at ?? null,
      nextInteractionName,
      nextInteractionRefId,
      nextInteractionIcon,
      nextInteractionColor,
      isActive: parsed.isActive ?? true,
      temperature: parsed.temperature ?? null,
      renewalQuarter: parsed.renewalQuarter ?? null
    });
    const profile = em.create(CustomerCompanyProfile, {
      organizationId: parsed.organizationId,
      tenantId: parsed.tenantId,
      entity,
      legalName: parsed.legalName ?? null,
      brandName: parsed.brandName ?? null,
      domain: parsed.domain ?? null,
      websiteUrl: parsed.websiteUrl ?? null,
      industry: parsed.industry ?? null,
      sizeBucket: parsed.sizeBucket ?? null,
      annualRevenue: parsed.annualRevenue !== void 0 && parsed.annualRevenue !== null ? String(parsed.annualRevenue) : null
    });
    await withAtomicFlush(em, [
      () => {
        em.persist(entity);
        em.persist(profile);
      },
      () => syncEntityTags(em, entity, parsed.tags)
    ], { transaction: true });
    await setCompanyCustomFields(ctx, entity.id, profile.id, entity.organizationId, entity.tenantId, custom);
    const de = ctx.container.resolve("dataEngine");
    await emitCrudSideEffects({
      dataEngine: de,
      action: "created",
      entity,
      identifiers: {
        id: profile.id ?? entity.id,
        organizationId: entity.organizationId,
        tenantId: entity.tenantId
      },
      indexer: companyCrudIndexer,
      events: companyCrudEvents
    });
    await emitQueryIndexUpsertEvents(ctx, [companyEntityIndexEntry(entity)]);
    return { entityId: entity.id, companyId: profile.id };
  },
  captureAfter: async (_input, result, ctx) => {
    const em = ctx.container.resolve("em").fork();
    return await loadCompanySnapshot(em, result.entityId);
  },
  buildLog: async ({ result, snapshots }) => {
    const { translate } = await resolveTranslations();
    const snapshot = snapshots.after;
    return {
      actionLabel: translate("customers.audit.companies.create", "Create company"),
      resourceKind: "customers.company",
      resourceId: result.entityId,
      tenantId: snapshot?.entity.tenantId ?? null,
      organizationId: snapshot?.entity.organizationId ?? null,
      snapshotAfter: snapshot ?? null,
      payload: {
        undo: {
          after: snapshot
        }
      }
    };
  },
  undo: async ({ logEntry, ctx }) => {
    const payload = extractUndoPayload(logEntry) ?? null;
    const entityId = logEntry?.resourceId;
    if (!entityId) return;
    const em = ctx.container.resolve("em").fork();
    const entity = await em.findOne(CustomerEntity, { id: entityId });
    if (!entity) return;
    const profile = await em.findOne(CustomerCompanyProfile, { entity });
    const identifiers = {
      id: payload?.after?.profile.id ?? profile?.id ?? entity.id,
      organizationId: entity.organizationId,
      tenantId: entity.tenantId
    };
    await withAtomicFlush(em, [
      async () => {
        await em.nativeDelete(CustomerCompanyProfile, { entity, organizationId: entity.organizationId, tenantId: entity.tenantId });
        await em.nativeDelete(CustomerTagAssignment, { entity, organizationId: entity.organizationId, tenantId: entity.tenantId });
        em.remove(entity);
      }
    ], { transaction: true });
    const de = ctx.container.resolve("dataEngine");
    await emitCrudUndoSideEffects({
      dataEngine: de,
      action: "deleted",
      entity,
      identifiers,
      indexer: companyCrudIndexer,
      events: companyCrudEvents
    });
    await emitQueryIndexDeleteEvents(ctx, [companyEntityIndexEntry(entity)]);
  },
  redo: async ({ logEntry, ctx }) => {
    const after = resolveRedoSnapshot(logEntry);
    if (!after) {
      throw new CrudHttpError(400, { error: "[internal] redo snapshot unavailable for company create" });
    }
    const em = ctx.container.resolve("em").fork();
    let entity = await findOneWithDecryption(
      em,
      CustomerEntity,
      { id: after.entity.id },
      void 0,
      { tenantId: after.entity.tenantId, organizationId: after.entity.organizationId }
    );
    if (!entity) {
      entity = em.create(CustomerEntity, {
        id: after.entity.id,
        organizationId: after.entity.organizationId,
        tenantId: after.entity.tenantId,
        kind: "company",
        displayName: after.entity.displayName,
        description: after.entity.description,
        ownerUserId: after.entity.ownerUserId,
        primaryEmail: after.entity.primaryEmail,
        primaryPhone: after.entity.primaryPhone,
        status: after.entity.status,
        lifecycleStage: after.entity.lifecycleStage,
        source: after.entity.source,
        temperature: after.entity.temperature,
        renewalQuarter: after.entity.renewalQuarter,
        nextInteractionAt: after.entity.nextInteractionAt,
        nextInteractionName: after.entity.nextInteractionName,
        nextInteractionRefId: after.entity.nextInteractionRefId,
        nextInteractionIcon: after.entity.nextInteractionIcon,
        nextInteractionColor: after.entity.nextInteractionColor,
        isActive: after.entity.isActive
      });
      em.persist(entity);
    }
    entity.deletedAt = null;
    entity.displayName = after.entity.displayName;
    entity.description = after.entity.description;
    entity.ownerUserId = after.entity.ownerUserId;
    entity.primaryEmail = after.entity.primaryEmail;
    entity.primaryPhone = after.entity.primaryPhone;
    entity.status = after.entity.status;
    entity.lifecycleStage = after.entity.lifecycleStage;
    entity.source = after.entity.source;
    entity.temperature = after.entity.temperature;
    entity.renewalQuarter = after.entity.renewalQuarter;
    entity.nextInteractionAt = after.entity.nextInteractionAt;
    entity.nextInteractionName = after.entity.nextInteractionName;
    entity.nextInteractionRefId = after.entity.nextInteractionRefId;
    entity.nextInteractionIcon = after.entity.nextInteractionIcon;
    entity.nextInteractionColor = after.entity.nextInteractionColor;
    entity.isActive = after.entity.isActive;
    const restoredEntity = entity;
    let profile = await findOneWithDecryption(
      em,
      CustomerCompanyProfile,
      { entity: restoredEntity },
      void 0,
      { tenantId: after.entity.tenantId, organizationId: after.entity.organizationId }
    );
    if (!profile) {
      profile = em.create(CustomerCompanyProfile, {
        id: after.profile.id,
        organizationId: after.entity.organizationId,
        tenantId: after.entity.tenantId,
        entity: restoredEntity,
        legalName: after.profile.legalName,
        brandName: after.profile.brandName,
        domain: after.profile.domain,
        websiteUrl: after.profile.websiteUrl,
        industry: after.profile.industry,
        sizeBucket: after.profile.sizeBucket,
        annualRevenue: after.profile.annualRevenue
      });
      em.persist(profile);
    } else {
      profile.legalName = after.profile.legalName;
      profile.brandName = after.profile.brandName;
      profile.domain = after.profile.domain;
      profile.websiteUrl = after.profile.websiteUrl;
      profile.industry = after.profile.industry;
      profile.sizeBucket = after.profile.sizeBucket;
      profile.annualRevenue = after.profile.annualRevenue;
    }
    const restoredProfile = profile;
    await withAtomicFlush(em, [
      () => syncEntityTags(em, restoredEntity, after.tagIds)
    ], { transaction: true });
    const restoreValues = buildCustomFieldResetMap(after.custom, void 0);
    if (Object.keys(restoreValues).length) {
      await setCompanyCustomFields(ctx, restoredEntity.id, restoredProfile.id, restoredEntity.organizationId, restoredEntity.tenantId, restoreValues);
    }
    const de = ctx.container.resolve("dataEngine");
    await emitCrudSideEffects({
      dataEngine: de,
      action: "created",
      entity: restoredEntity,
      identifiers: {
        id: restoredProfile.id ?? restoredEntity.id,
        organizationId: restoredEntity.organizationId,
        tenantId: restoredEntity.tenantId
      },
      indexer: companyCrudIndexer,
      events: companyCrudEvents
    });
    await emitQueryIndexUpsertEvents(ctx, [companyEntityIndexEntry(restoredEntity)]);
    return { entityId: restoredEntity.id, companyId: restoredProfile.id };
  }
};
const updateCompanyCommand = {
  id: "customers.companies.update",
  async prepare(rawInput, ctx) {
    const { parsed } = parseWithCustomFields(companyUpdateSchema, rawInput);
    const em = ctx.container.resolve("em");
    const snapshot = await loadCompanySnapshot(em, parsed.id);
    return snapshot ? { before: snapshot } : {};
  },
  async execute(rawInput, ctx) {
    const { parsed, custom } = parseWithCustomFields(companyUpdateSchema, rawInput);
    const em = ctx.container.resolve("em").fork();
    const entity = await em.findOne(CustomerEntity, { id: parsed.id, deletedAt: null });
    const record = assertFound(entity, "Company not found");
    ensureTenantScope(ctx, record.tenantId);
    ensureOrganizationScope(ctx, record.organizationId);
    const profile = await em.findOne(CustomerCompanyProfile, { entity: record });
    if (!profile) throw new CrudHttpError(404, { error: "Company profile not found" });
    await withAtomicFlush(em, [
      () => {
        if (parsed.displayName !== void 0) record.displayName = parsed.displayName;
        if (parsed.description !== void 0) record.description = parsed.description ?? null;
        if (parsed.ownerUserId !== void 0) record.ownerUserId = parsed.ownerUserId ?? null;
        if (parsed.primaryEmail !== void 0) record.primaryEmail = parsed.primaryEmail ?? null;
        if (parsed.primaryPhone !== void 0) record.primaryPhone = normalizeOptionalString(parsed.primaryPhone);
        if (parsed.status !== void 0) record.status = parsed.status ?? null;
        if (parsed.lifecycleStage !== void 0) record.lifecycleStage = parsed.lifecycleStage ?? null;
        if (parsed.source !== void 0) record.source = parsed.source ?? null;
        if (parsed.isActive !== void 0) record.isActive = parsed.isActive;
        if (parsed.temperature !== void 0) record.temperature = parsed.temperature ?? null;
        if (parsed.renewalQuarter !== void 0) record.renewalQuarter = parsed.renewalQuarter ?? null;
        if (parsed.nextInteraction) {
          record.nextInteractionAt = parsed.nextInteraction.at;
          record.nextInteractionName = parsed.nextInteraction.name.trim();
          record.nextInteractionRefId = normalizeOptionalString(parsed.nextInteraction.refId) ?? null;
          record.nextInteractionIcon = normalizeOptionalString(parsed.nextInteraction.icon);
          record.nextInteractionColor = normalizeHexColor(parsed.nextInteraction.color);
        } else if (parsed.nextInteraction === null) {
          record.nextInteractionAt = null;
          record.nextInteractionName = null;
          record.nextInteractionRefId = null;
          record.nextInteractionIcon = null;
          record.nextInteractionColor = null;
        }
        if (parsed.legalName !== void 0) profile.legalName = parsed.legalName ?? null;
        if (parsed.brandName !== void 0) profile.brandName = parsed.brandName ?? null;
        if (parsed.domain !== void 0) profile.domain = parsed.domain ?? null;
        if (parsed.websiteUrl !== void 0) profile.websiteUrl = parsed.websiteUrl ?? null;
        if (parsed.industry !== void 0) profile.industry = parsed.industry ?? null;
        if (parsed.sizeBucket !== void 0) profile.sizeBucket = parsed.sizeBucket ?? null;
        if (parsed.annualRevenue !== void 0) {
          profile.annualRevenue = parsed.annualRevenue !== null && parsed.annualRevenue !== void 0 ? String(parsed.annualRevenue) : null;
        }
      },
      () => syncEntityTags(em, record, parsed.tags)
    ], { transaction: true });
    await setCompanyCustomFields(ctx, record.id, profile.id, record.organizationId, record.tenantId, custom);
    const de = ctx.container.resolve("dataEngine");
    await emitCrudSideEffects({
      dataEngine: de,
      action: "updated",
      entity: record,
      identifiers: {
        id: profile.id ?? record.id,
        organizationId: record.organizationId,
        tenantId: record.tenantId
      },
      indexer: companyCrudIndexer,
      events: companyCrudEvents
    });
    await emitQueryIndexUpsertEvents(ctx, [companyEntityIndexEntry(record)]);
    return { entityId: record.id, updatedAt: record.updatedAt };
  },
  captureAfter: async (_input, result, ctx) => {
    const em = ctx.container.resolve("em").fork();
    return await loadCompanySnapshot(em, result.entityId);
  },
  buildLog: async ({ snapshots }) => {
    const { translate } = await resolveTranslations();
    const before = snapshots.before;
    if (!before) return null;
    const afterSnapshot = snapshots.after;
    if (afterSnapshot && snapshotsEqual(before, afterSnapshot)) {
      return { skipLog: true };
    }
    return {
      actionLabel: translate("customers.audit.companies.update", "Update company"),
      resourceKind: "customers.company",
      resourceId: before.entity.id,
      tenantId: before.entity.tenantId,
      organizationId: before.entity.organizationId,
      snapshotBefore: before,
      snapshotAfter: afterSnapshot ?? null,
      payload: {
        undo: {
          before,
          after: afterSnapshot ?? null
        }
      }
    };
  },
  undo: async ({ logEntry, ctx }) => {
    const payload = extractUndoPayload(logEntry);
    const before = payload?.before;
    if (!before) return;
    const em = ctx.container.resolve("em").fork();
    let entity = await em.findOne(CustomerEntity, { id: before.entity.id });
    if (!entity) {
      entity = em.create(CustomerEntity, {
        id: before.entity.id,
        organizationId: before.entity.organizationId,
        tenantId: before.entity.tenantId,
        kind: "company",
        displayName: before.entity.displayName,
        description: before.entity.description,
        ownerUserId: before.entity.ownerUserId,
        primaryEmail: before.entity.primaryEmail,
        primaryPhone: before.entity.primaryPhone,
        status: before.entity.status,
        lifecycleStage: before.entity.lifecycleStage,
        source: before.entity.source,
        temperature: before.entity.temperature,
        renewalQuarter: before.entity.renewalQuarter,
        nextInteractionAt: before.entity.nextInteractionAt,
        nextInteractionName: before.entity.nextInteractionName,
        nextInteractionRefId: before.entity.nextInteractionRefId,
        nextInteractionIcon: before.entity.nextInteractionIcon,
        nextInteractionColor: before.entity.nextInteractionColor,
        isActive: before.entity.isActive
      });
      em.persist(entity);
    } else {
      entity.displayName = before.entity.displayName;
      entity.description = before.entity.description;
      entity.ownerUserId = before.entity.ownerUserId;
      entity.primaryEmail = before.entity.primaryEmail;
      entity.primaryPhone = before.entity.primaryPhone;
      entity.status = before.entity.status;
      entity.lifecycleStage = before.entity.lifecycleStage;
      entity.source = before.entity.source;
      entity.temperature = before.entity.temperature;
      entity.renewalQuarter = before.entity.renewalQuarter;
      entity.nextInteractionAt = before.entity.nextInteractionAt;
      entity.nextInteractionName = before.entity.nextInteractionName;
      entity.nextInteractionRefId = before.entity.nextInteractionRefId;
      entity.nextInteractionIcon = before.entity.nextInteractionIcon;
      entity.nextInteractionColor = before.entity.nextInteractionColor;
      entity.isActive = before.entity.isActive;
    }
    await em.flush();
    let profile = await em.findOne(CustomerCompanyProfile, { entity });
    if (!profile) {
      profile = em.create(CustomerCompanyProfile, {
        id: before.profile.id,
        organizationId: before.entity.organizationId,
        tenantId: before.entity.tenantId,
        entity,
        legalName: before.profile.legalName,
        brandName: before.profile.brandName,
        domain: before.profile.domain,
        websiteUrl: before.profile.websiteUrl,
        industry: before.profile.industry,
        sizeBucket: before.profile.sizeBucket,
        annualRevenue: before.profile.annualRevenue
      });
      em.persist(profile);
    } else {
      profile.legalName = before.profile.legalName;
      profile.brandName = before.profile.brandName;
      profile.domain = before.profile.domain;
      profile.websiteUrl = before.profile.websiteUrl;
      profile.industry = before.profile.industry;
      profile.sizeBucket = before.profile.sizeBucket;
      profile.annualRevenue = before.profile.annualRevenue;
    }
    await em.flush();
    await syncEntityTags(em, entity, before.tagIds);
    await em.flush();
    await em.nativeDelete(CustomerDealCompanyLink, { company: entity });
    if (before.deals?.length) {
      const dealIds = before.deals.map((link) => link.dealId);
      const deals = await em.find(CustomerDeal, {
        id: { $in: dealIds },
        organizationId: entity.organizationId,
        tenantId: entity.tenantId
      });
      const dealMap = new Map(deals.map((deal) => [deal.id, deal]));
      for (const link of before.deals) {
        const deal = dealMap.get(link.dealId);
        if (!deal) continue;
        const restoredLink = em.create(CustomerDealCompanyLink, {
          id: link.id,
          deal,
          company: entity,
          createdAt: link.createdAt
        });
        em.persist(restoredLink);
      }
      await em.flush();
    }
    if (before.members?.length) {
      const memberIds = before.members.map((member) => member.profileId);
      const profiles = await em.find(CustomerPersonProfile, {
        id: { $in: memberIds },
        organizationId: entity.organizationId,
        tenantId: entity.tenantId
      });
      const profileMap = new Map(profiles.map((profile2) => [profile2.id, profile2]));
      for (const member of before.members) {
        const profile2 = profileMap.get(member.profileId);
        if (!profile2) continue;
        profile2.company = entity;
      }
      await em.flush();
    }
    const de = ctx.container.resolve("dataEngine");
    await emitCrudUndoSideEffects({
      dataEngine: de,
      action: "updated",
      entity,
      identifiers: {
        id: profile.id ?? entity.id,
        organizationId: entity.organizationId,
        tenantId: entity.tenantId
      },
      indexer: companyCrudIndexer,
      events: companyCrudEvents
    });
    await emitQueryIndexUpsertEvents(ctx, [companyEntityIndexEntry(entity)]);
    const resetValues = buildCustomFieldResetMap(before.custom, payload?.after?.custom);
    if (Object.keys(resetValues).length) {
      await setCompanyCustomFields(ctx, entity.id, profile.id, entity.organizationId, entity.tenantId, resetValues);
    }
  }
};
const deleteCompanyCommand = {
  id: "customers.companies.delete",
  async prepare(input, ctx) {
    const id = requireId(input, "Company id required");
    const em = ctx.container.resolve("em");
    const snapshot = await loadCompanySnapshot(em, id);
    return snapshot ? { before: snapshot } : {};
  },
  async execute(input, ctx) {
    const id = requireId(input, "Company id required");
    const baseEm = ctx.container.resolve("em").fork();
    const snapshot = await loadCompanySnapshot(baseEm, id);
    const entity = await baseEm.findOne(CustomerEntity, { id, deletedAt: null });
    const record = assertFound(entity, "Company not found");
    ensureTenantScope(ctx, record.tenantId);
    ensureOrganizationScope(ctx, record.organizationId);
    const dependentScope = {
      organizationId: record.organizationId,
      tenantId: record.tenantId
    };
    const personLinks = await baseEm.count(CustomerPersonCompanyLink, {
      company: record,
      deletedAt: null,
      ...dependentScope
    });
    const dealLinks = await baseEm.count(CustomerDealCompanyLink, {
      company: record
    });
    const directPeople = await baseEm.count(CustomerPersonProfile, {
      company: record,
      ...dependentScope
    });
    if (personLinks > 0 || dealLinks > 0 || directPeople > 0) {
      const { translate } = await resolveTranslations();
      throw buildCompanyHasDependentsError(translate, { personLinks, dealLinks, directPeople });
    }
    const profile = await baseEm.findOne(CustomerCompanyProfile, { entity: record });
    await baseEm.transactional(async (em) => {
      const recheckPersonLinks = await em.count(CustomerPersonCompanyLink, {
        company: record,
        deletedAt: null,
        ...dependentScope
      });
      const recheckDealLinks = await em.count(CustomerDealCompanyLink, {
        company: record
      });
      const recheckDirectPeople = await em.count(CustomerPersonProfile, {
        company: record,
        ...dependentScope
      });
      if (recheckPersonLinks > 0 || recheckDealLinks > 0 || recheckDirectPeople > 0) {
        const { translate } = await resolveTranslations();
        throw buildCompanyHasDependentsError(translate, {
          personLinks: recheckPersonLinks,
          dealLinks: recheckDealLinks,
          directPeople: recheckDirectPeople
        });
      }
      await em.nativeUpdate(CustomerPersonProfile, { company: record }, { company: null });
      await em.nativeDelete(CustomerDealCompanyLink, { company: record });
      await em.nativeDelete(CustomerActivity, { entity: record, organizationId: record.organizationId, tenantId: record.tenantId });
      await em.nativeDelete(CustomerInteraction, { entity: record, organizationId: record.organizationId, tenantId: record.tenantId });
      await em.nativeDelete(CustomerTodoLink, { entity: record, organizationId: record.organizationId, tenantId: record.tenantId });
      await em.nativeDelete(CustomerCompanyProfile, { entity: record, organizationId: record.organizationId, tenantId: record.tenantId });
      await em.nativeDelete(CustomerAddress, { entity: record, organizationId: record.organizationId, tenantId: record.tenantId });
      await em.nativeDelete(CustomerComment, { entity: record, organizationId: record.organizationId, tenantId: record.tenantId });
      await em.nativeDelete(CustomerTagAssignment, { entity: record, organizationId: record.organizationId, tenantId: record.tenantId });
      if (profile) {
        await em.nativeDelete(CustomFieldValue, { entityId: COMPANY_ENTITY_ID, recordId: profile.id });
      }
      await em.nativeDelete(CustomFieldValue, { entityId: CUSTOMER_ENTITY_ID, recordId: record.id });
      const txEntity = await findOneWithDecryption(
        em,
        CustomerEntity,
        { id: record.id },
        void 0,
        { tenantId: record.tenantId, organizationId: record.organizationId }
      );
      if (txEntity) em.remove(txEntity);
    });
    const indexDeletes = [];
    const memberUpserts = [];
    const dealUpserts = [];
    if (snapshot) {
      for (const activity of snapshot.activities ?? []) {
        indexDeletes.push({
          entityType: E.customers.customer_activity,
          recordId: activity.id,
          tenantId: record.tenantId,
          organizationId: record.organizationId
        });
      }
      for (const comment of snapshot.comments ?? []) {
        indexDeletes.push({
          entityType: E.customers.customer_comment,
          recordId: comment.id,
          tenantId: record.tenantId,
          organizationId: record.organizationId
        });
      }
      for (const address of snapshot.addresses ?? []) {
        indexDeletes.push({
          entityType: E.customers.customer_address,
          recordId: address.id,
          tenantId: record.tenantId,
          organizationId: record.organizationId
        });
      }
      for (const todo of snapshot.todos ?? []) {
        indexDeletes.push({
          entityType: E.customers.customer_todo_link,
          recordId: todo.id,
          tenantId: record.tenantId,
          organizationId: record.organizationId
        });
      }
      for (const interaction of snapshot.interactions ?? []) {
        indexDeletes.push({
          entityType: E.customers.customer_interaction,
          recordId: interaction.id,
          tenantId: record.tenantId,
          organizationId: record.organizationId
        });
      }
      for (const member of snapshot.members ?? []) {
        if (member.profileId) {
          memberUpserts.push({
            entityType: E.customers.customer_person_profile,
            recordId: member.profileId,
            tenantId: record.tenantId,
            organizationId: record.organizationId
          });
        }
      }
      for (const deal of snapshot.deals ?? []) {
        if (deal.dealId) {
          dealUpserts.push({
            entityType: E.customers.customer_deal,
            recordId: deal.dealId,
            tenantId: record.tenantId,
            organizationId: record.organizationId
          });
        }
      }
    }
    const de = ctx.container.resolve("dataEngine");
    await emitCrudSideEffects({
      dataEngine: de,
      action: "deleted",
      entity: record,
      identifiers: {
        id: profile?.id ?? record.id,
        organizationId: record.organizationId,
        tenantId: record.tenantId
      },
      indexer: companyCrudIndexer,
      events: companyCrudEvents
    });
    await emitQueryIndexDeleteEvents(ctx, [companyEntityIndexEntry(record)]);
    await emitQueryIndexDeleteEvents(ctx, indexDeletes);
    await emitQueryIndexUpsertEvents(ctx, memberUpserts);
    await emitQueryIndexUpsertEvents(ctx, dealUpserts);
    return { entityId: record.id };
  },
  buildLog: async ({ snapshots }) => {
    const before = snapshots.before;
    if (!before) return null;
    const { translate } = await resolveTranslations();
    return {
      actionLabel: translate("customers.audit.companies.delete", "Delete company"),
      resourceKind: "customers.company",
      resourceId: before.entity.id,
      tenantId: before.entity.tenantId,
      organizationId: before.entity.organizationId,
      snapshotBefore: before,
      payload: {
        undo: {
          before
        }
      }
    };
  },
  undo: async ({ logEntry, ctx }) => {
    const payload = extractUndoPayload(logEntry);
    const before = payload?.before;
    if (!before) return;
    const em = ctx.container.resolve("em").fork();
    let entity = await em.findOne(CustomerEntity, { id: before.entity.id });
    if (!entity) {
      entity = em.create(CustomerEntity, {
        id: before.entity.id,
        organizationId: before.entity.organizationId,
        tenantId: before.entity.tenantId,
        kind: "company",
        displayName: before.entity.displayName,
        description: before.entity.description,
        ownerUserId: before.entity.ownerUserId,
        primaryEmail: before.entity.primaryEmail,
        primaryPhone: before.entity.primaryPhone,
        status: before.entity.status,
        lifecycleStage: before.entity.lifecycleStage,
        source: before.entity.source,
        temperature: before.entity.temperature,
        renewalQuarter: before.entity.renewalQuarter,
        nextInteractionAt: before.entity.nextInteractionAt,
        nextInteractionName: before.entity.nextInteractionName,
        nextInteractionRefId: before.entity.nextInteractionRefId,
        nextInteractionIcon: before.entity.nextInteractionIcon,
        nextInteractionColor: before.entity.nextInteractionColor,
        isActive: before.entity.isActive
      });
      em.persist(entity);
    }
    entity.displayName = before.entity.displayName;
    entity.description = before.entity.description;
    entity.ownerUserId = before.entity.ownerUserId;
    entity.primaryEmail = before.entity.primaryEmail;
    entity.primaryPhone = before.entity.primaryPhone;
    entity.status = before.entity.status;
    entity.lifecycleStage = before.entity.lifecycleStage;
    entity.source = before.entity.source;
    entity.temperature = before.entity.temperature;
    entity.renewalQuarter = before.entity.renewalQuarter;
    entity.nextInteractionAt = before.entity.nextInteractionAt;
    entity.nextInteractionName = before.entity.nextInteractionName;
    entity.nextInteractionRefId = before.entity.nextInteractionRefId;
    entity.nextInteractionIcon = before.entity.nextInteractionIcon;
    entity.nextInteractionColor = before.entity.nextInteractionColor;
    entity.isActive = before.entity.isActive;
    entity.deletedAt = null;
    let profile = await em.findOne(CustomerCompanyProfile, { entity });
    if (!profile) {
      profile = em.create(CustomerCompanyProfile, {
        id: before.profile.id,
        organizationId: before.entity.organizationId,
        tenantId: before.entity.tenantId,
        entity,
        legalName: before.profile.legalName,
        brandName: before.profile.brandName,
        domain: before.profile.domain,
        websiteUrl: before.profile.websiteUrl,
        industry: before.profile.industry,
        sizeBucket: before.profile.sizeBucket,
        annualRevenue: before.profile.annualRevenue
      });
      em.persist(profile);
    } else {
      profile.legalName = before.profile.legalName;
      profile.brandName = before.profile.brandName;
      profile.domain = before.profile.domain;
      profile.websiteUrl = before.profile.websiteUrl;
      profile.industry = before.profile.industry;
      profile.sizeBucket = before.profile.sizeBucket;
      profile.annualRevenue = before.profile.annualRevenue;
    }
    const beforeDeals = before.deals ?? [];
    const beforeMembers = before.members ?? [];
    const beforeActivities = before.activities ?? [];
    const beforeComments = before.comments ?? [];
    const beforeAddresses = before.addresses ?? [];
    const beforeTodos = before.todos ?? [];
    const beforeInteractions = before.interactions ?? [];
    let dealMap = /* @__PURE__ */ new Map();
    await withAtomicFlush(em, [
      () => syncEntityTags(em, entity, before.tagIds),
      async () => {
        const relatedDealIds = /* @__PURE__ */ new Set();
        for (const link of beforeDeals) relatedDealIds.add(link.dealId);
        for (const activity of beforeActivities) {
          if (activity.dealId) relatedDealIds.add(activity.dealId);
        }
        for (const comment of beforeComments) {
          if (comment.dealId) relatedDealIds.add(comment.dealId);
        }
        if (relatedDealIds.size) {
          const deals = await em.find(CustomerDeal, {
            id: { $in: Array.from(relatedDealIds) },
            organizationId: entity.organizationId,
            tenantId: entity.tenantId
          });
          dealMap = new Map(deals.map((deal) => [deal.id, deal]));
        }
        await em.nativeDelete(CustomerDealCompanyLink, { company: entity });
        for (const link of beforeDeals) {
          const deal = dealMap.get(link.dealId);
          if (!deal) continue;
          const restoredLink = em.create(CustomerDealCompanyLink, {
            id: link.id,
            deal,
            company: entity,
            createdAt: link.createdAt
          });
          em.persist(restoredLink);
        }
        if (beforeMembers.length) {
          const memberIds = beforeMembers.map((member) => member.profileId);
          const profiles = await em.find(CustomerPersonProfile, {
            id: { $in: memberIds },
            organizationId: entity.organizationId,
            tenantId: entity.tenantId
          });
          const profileMap = new Map(profiles.map((profile2) => [profile2.id, profile2]));
          for (const member of beforeMembers) {
            const memberProfile = profileMap.get(member.profileId);
            if (!memberProfile) continue;
            memberProfile.company = entity;
          }
        }
        await em.nativeDelete(CustomerActivity, { entity, organizationId: entity.organizationId, tenantId: entity.tenantId });
        for (const activity of beforeActivities) {
          const restoredActivity = em.create(CustomerActivity, {
            id: activity.id,
            organizationId: entity.organizationId,
            tenantId: entity.tenantId,
            entity,
            activityType: activity.activityType,
            subject: activity.subject,
            body: activity.body,
            occurredAt: activity.occurredAt,
            authorUserId: activity.authorUserId,
            appearanceIcon: activity.appearanceIcon,
            appearanceColor: activity.appearanceColor,
            deal: activity.dealId ? dealMap.get(activity.dealId) ?? null : null,
            createdAt: activity.createdAt,
            updatedAt: activity.updatedAt
          });
          em.persist(restoredActivity);
        }
        await em.nativeDelete(CustomerComment, { entity, organizationId: entity.organizationId, tenantId: entity.tenantId });
        for (const comment of beforeComments) {
          const restoredComment = em.create(CustomerComment, {
            id: comment.id,
            organizationId: entity.organizationId,
            tenantId: entity.tenantId,
            entity,
            body: comment.body,
            authorUserId: comment.authorUserId,
            appearanceIcon: comment.appearanceIcon,
            appearanceColor: comment.appearanceColor,
            deal: comment.dealId ? dealMap.get(comment.dealId) ?? null : null,
            createdAt: comment.createdAt,
            updatedAt: comment.updatedAt,
            deletedAt: comment.deletedAt
          });
          em.persist(restoredComment);
        }
        await em.nativeDelete(CustomerAddress, { entity, organizationId: entity.organizationId, tenantId: entity.tenantId });
        for (const address of beforeAddresses) {
          const restoredAddress = em.create(CustomerAddress, {
            id: address.id,
            organizationId: entity.organizationId,
            tenantId: entity.tenantId,
            entity,
            name: address.name,
            purpose: address.purpose,
            addressLine1: address.addressLine1,
            addressLine2: address.addressLine2,
            city: address.city,
            region: address.region,
            postalCode: address.postalCode,
            country: address.country,
            latitude: address.latitude,
            longitude: address.longitude,
            isPrimary: address.isPrimary
          });
          em.persist(restoredAddress);
        }
        await em.nativeDelete(CustomerTodoLink, { entity, organizationId: entity.organizationId, tenantId: entity.tenantId });
        for (const todo of beforeTodos) {
          const restoredTodo = em.create(CustomerTodoLink, {
            id: todo.id,
            organizationId: entity.organizationId,
            tenantId: entity.tenantId,
            entity,
            todoId: todo.todoId,
            todoSource: todo.todoSource,
            createdAt: todo.createdAt,
            createdByUserId: todo.createdByUserId
          });
          em.persist(restoredTodo);
        }
        await em.nativeDelete(CustomerInteraction, { entity, organizationId: entity.organizationId, tenantId: entity.tenantId });
        for (const interaction of beforeInteractions) {
          const restoredInteraction = em.create(CustomerInteraction, {
            id: interaction.id,
            organizationId: entity.organizationId,
            tenantId: entity.tenantId,
            entity,
            interactionType: interaction.interactionType,
            title: interaction.title,
            body: interaction.body,
            status: interaction.status,
            scheduledAt: interaction.scheduledAt,
            occurredAt: interaction.occurredAt,
            priority: interaction.priority,
            authorUserId: interaction.authorUserId,
            ownerUserId: interaction.ownerUserId,
            dealId: interaction.dealId,
            source: interaction.source,
            appearanceIcon: interaction.appearanceIcon,
            appearanceColor: interaction.appearanceColor,
            createdAt: interaction.createdAt,
            updatedAt: interaction.updatedAt,
            deletedAt: interaction.deletedAt
          });
          em.persist(restoredInteraction);
        }
      }
    ], { transaction: true });
    const de = ctx.container.resolve("dataEngine");
    for (const interaction of beforeInteractions) {
      if (!interaction.custom || !Object.keys(interaction.custom).length) continue;
      await setCustomFieldsIfAny({
        dataEngine: de,
        entityId: INTERACTION_ENTITY_ID,
        recordId: interaction.id,
        organizationId: entity.organizationId,
        tenantId: entity.tenantId,
        values: interaction.custom,
        notify: false
      });
    }
    await emitCrudUndoSideEffects({
      dataEngine: de,
      action: "created",
      entity,
      identifiers: {
        id: profile.id ?? entity.id,
        organizationId: entity.organizationId,
        tenantId: entity.tenantId
      },
      indexer: companyCrudIndexer,
      events: companyCrudEvents
    });
    const childUpserts = [];
    for (const activity of beforeActivities ?? []) {
      childUpserts.push({
        entityType: E.customers.customer_activity,
        recordId: activity.id,
        tenantId: entity.tenantId,
        organizationId: entity.organizationId
      });
    }
    for (const comment of beforeComments ?? []) {
      childUpserts.push({
        entityType: E.customers.customer_comment,
        recordId: comment.id,
        tenantId: entity.tenantId,
        organizationId: entity.organizationId
      });
    }
    for (const address of beforeAddresses ?? []) {
      childUpserts.push({
        entityType: E.customers.customer_address,
        recordId: address.id,
        tenantId: entity.tenantId,
        organizationId: entity.organizationId
      });
    }
    for (const todo of beforeTodos ?? []) {
      childUpserts.push({
        entityType: E.customers.customer_todo_link,
        recordId: todo.id,
        tenantId: entity.tenantId,
        organizationId: entity.organizationId
      });
    }
    for (const interaction of beforeInteractions ?? []) {
      childUpserts.push({
        entityType: E.customers.customer_interaction,
        recordId: interaction.id,
        tenantId: entity.tenantId,
        organizationId: entity.organizationId
      });
    }
    const memberUpserts = [];
    for (const member of beforeMembers ?? []) {
      if (member.profileId) {
        memberUpserts.push({
          entityType: E.customers.customer_person_profile,
          recordId: member.profileId,
          tenantId: entity.tenantId,
          organizationId: entity.organizationId
        });
      }
    }
    const dealUpserts = [];
    for (const deal of beforeDeals ?? []) {
      if (deal.dealId) {
        dealUpserts.push({
          entityType: E.customers.customer_deal,
          recordId: deal.dealId,
          tenantId: entity.tenantId,
          organizationId: entity.organizationId
        });
      }
    }
    const resetValues = buildCustomFieldResetMap(before.custom, void 0);
    if (Object.keys(resetValues).length) {
      await setCompanyCustomFields(ctx, entity.id, profile.id, entity.organizationId, entity.tenantId, resetValues);
    }
    await emitQueryIndexUpsertEvents(ctx, [companyEntityIndexEntry(entity)]);
    await emitQueryIndexUpsertEvents(ctx, childUpserts);
    await emitQueryIndexUpsertEvents(ctx, memberUpserts);
    await emitQueryIndexUpsertEvents(ctx, dealUpserts);
  }
};
registerCommand(createCompanyCommand);
registerCommand(updateCompanyCommand);
registerCommand(deleteCompanyCommand);
//# sourceMappingURL=companies.js.map
