import { withAtomicFlush } from "./flush.js";
import { setCustomFieldsIfAny, emitCrudSideEffects } from "./helpers.js";
async function runCrudCommandWrite(opts) {
  const em = opts.em ?? opts.ctx.container.resolve("em").fork();
  const transaction = opts.transaction ?? true;
  await withAtomicFlush(
    em,
    opts.phases.map((phase) => () => phase({ em })),
    { transaction }
  );
  const dataEngine = opts.dataEngine ?? opts.ctx.container.resolve("dataEngine");
  const target = opts.sideEffect();
  if (opts.customFields && Object.keys(opts.customFields).length > 0) {
    await setCustomFieldsIfAny({
      dataEngine,
      entityId: opts.entityId,
      recordId: target.identifiers.id,
      tenantId: opts.scope.tenantId,
      organizationId: opts.scope.organizationId,
      values: opts.customFields,
      notify: opts.notifyCustomFields ?? false
    });
  }
  await emitCrudSideEffects({
    dataEngine,
    action: opts.action,
    entity: target.entity,
    identifiers: target.identifiers,
    syncOrigin: opts.syncOrigin ?? null,
    events: opts.events,
    indexer: opts.indexer
  });
  return { em };
}
export {
  runCrudCommandWrite
};
//# sourceMappingURL=runCrudCommandWrite.js.map
