import { registerCommand } from "@open-mercato/shared/lib/commands";
import {
  buildChanges,
  requireId,
  parseWithCustomFields,
  setCustomFieldsIfAny,
  emitCrudSideEffects,
  emitCrudUndoSideEffects
} from "@open-mercato/shared/lib/commands/helpers";
import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
import { loadCustomFieldSnapshot, buildCustomFieldResetMap } from "@open-mercato/shared/lib/commands/customFieldSnapshots";
import { makeCreateRedo } from "@open-mercato/shared/lib/commands/redo";
import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
import { E } from "../../../generated/entities.ids.generated.js";
import {
  SalesChannel,
  SalesDeliveryWindow,
  SalesPaymentMethod,
  SalesShippingMethod,
  SalesTaxRate
} from "../data/entities.js";
import { resolveDictionaryEntryValue } from "../lib/dictionaries.js";
import {
  channelCreateSchema,
  channelUpdateSchema,
  deliveryWindowCreateSchema,
  deliveryWindowUpdateSchema,
  paymentMethodCreateSchema,
  paymentMethodUpdateSchema,
  shippingMethodCreateSchema,
  shippingMethodUpdateSchema,
  taxRateCreateSchema,
  taxRateUpdateSchema
} from "../data/validators.js";
import {
  assertFound,
  cloneJson,
  ensureOrganizationScope,
  ensureSameScope,
  ensureTenantScope,
  extractUndoPayload,
  toNumericString
} from "./shared.js";
function mergeProviderSettings(metadata, settings) {
  const base = metadata && typeof metadata === "object" ? cloneJson(metadata) : {};
  if (settings && typeof settings === "object" && Object.keys(settings).length > 0) {
    return { ...base, providerSettings: cloneJson(settings) };
  }
  return Object.keys(base).length ? base : null;
}
function readProviderSettings(metadata) {
  if (!metadata || typeof metadata !== "object") return null;
  const raw = metadata.providerSettings;
  if (raw && typeof raw === "object") {
    return cloneJson(raw);
  }
  return null;
}
const channelCrudEvents = {
  module: "sales",
  entity: "channel",
  persistent: true,
  buildPayload: (ctx) => ({
    id: ctx.identifiers.id,
    organizationId: ctx.identifiers.organizationId,
    tenantId: ctx.identifiers.tenantId
  })
};
const channelCrudIndexer = {
  entityType: E.sales.sales_channel
};
async function loadChannelSnapshot(em, id) {
  const channel = await findOneWithDecryption(em, SalesChannel, { id, deletedAt: null }, {});
  if (!channel) return null;
  const custom = await loadCustomFieldSnapshot(em, {
    entityId: E.sales.sales_channel,
    recordId: channel.id,
    tenantId: channel.tenantId,
    organizationId: channel.organizationId
  });
  return {
    id: channel.id,
    organizationId: channel.organizationId,
    tenantId: channel.tenantId,
    name: channel.name,
    code: channel.code ?? null,
    description: channel.description ?? null,
    statusEntryId: channel.statusEntryId ?? null,
    status: channel.status ?? null,
    websiteUrl: channel.websiteUrl ?? null,
    contactEmail: channel.contactEmail ?? null,
    contactPhone: channel.contactPhone ?? null,
    addressLine1: channel.addressLine1 ?? null,
    addressLine2: channel.addressLine2 ?? null,
    city: channel.city ?? null,
    region: channel.region ?? null,
    postalCode: channel.postalCode ?? null,
    country: channel.country ?? null,
    latitude: channel.latitude ?? null,
    longitude: channel.longitude ?? null,
    metadata: channel.metadata ? cloneJson(channel.metadata) : null,
    isActive: channel.isActive,
    custom: Object.keys(custom).length ? custom : null
  };
}
function channelSeedFromSnapshot(snapshot) {
  return {
    id: snapshot.id,
    organizationId: snapshot.organizationId,
    tenantId: snapshot.tenantId,
    name: snapshot.name,
    code: snapshot.code ?? null,
    description: snapshot.description ?? null,
    statusEntryId: snapshot.statusEntryId ?? null,
    status: snapshot.status ?? null,
    websiteUrl: snapshot.websiteUrl ?? null,
    contactEmail: snapshot.contactEmail ?? null,
    contactPhone: snapshot.contactPhone ?? null,
    addressLine1: snapshot.addressLine1 ?? null,
    addressLine2: snapshot.addressLine2 ?? null,
    city: snapshot.city ?? null,
    region: snapshot.region ?? null,
    postalCode: snapshot.postalCode ?? null,
    country: snapshot.country ?? null,
    latitude: snapshot.latitude ?? null,
    longitude: snapshot.longitude ?? null,
    metadata: snapshot.metadata ? cloneJson(snapshot.metadata) : null,
    isActive: snapshot.isActive,
    createdAt: /* @__PURE__ */ new Date(),
    updatedAt: /* @__PURE__ */ new Date()
  };
}
function deliveryWindowSeedFromSnapshot(snapshot) {
  return {
    id: snapshot.id,
    organizationId: snapshot.organizationId,
    tenantId: snapshot.tenantId,
    name: snapshot.name,
    code: snapshot.code,
    description: snapshot.description ?? null,
    leadTimeDays: snapshot.leadTimeDays ?? null,
    cutoffTime: snapshot.cutoffTime ?? null,
    timezone: snapshot.timezone ?? null,
    metadata: snapshot.metadata ? cloneJson(snapshot.metadata) : null,
    isActive: snapshot.isActive,
    createdAt: /* @__PURE__ */ new Date(),
    updatedAt: /* @__PURE__ */ new Date()
  };
}
function shippingMethodSeedFromSnapshot(snapshot) {
  return {
    id: snapshot.id,
    organizationId: snapshot.organizationId,
    tenantId: snapshot.tenantId,
    name: snapshot.name,
    code: snapshot.code,
    description: snapshot.description ?? null,
    carrierCode: snapshot.carrierCode ?? null,
    providerKey: snapshot.providerKey ?? null,
    serviceLevel: snapshot.serviceLevel ?? null,
    estimatedTransitDays: snapshot.estimatedTransitDays ?? null,
    baseRateNet: snapshot.baseRateNet,
    baseRateGross: snapshot.baseRateGross,
    currencyCode: snapshot.currencyCode ?? null,
    metadata: mergeProviderSettings(snapshot.metadata, snapshot.providerSettings),
    isActive: snapshot.isActive,
    createdAt: /* @__PURE__ */ new Date(),
    updatedAt: /* @__PURE__ */ new Date()
  };
}
function paymentMethodSeedFromSnapshot(snapshot) {
  return {
    id: snapshot.id,
    organizationId: snapshot.organizationId,
    tenantId: snapshot.tenantId,
    name: snapshot.name,
    code: snapshot.code,
    description: snapshot.description ?? null,
    providerKey: snapshot.providerKey ?? null,
    terms: snapshot.terms ?? null,
    metadata: mergeProviderSettings(snapshot.metadata, snapshot.providerSettings),
    isActive: snapshot.isActive,
    createdAt: /* @__PURE__ */ new Date(),
    updatedAt: /* @__PURE__ */ new Date()
  };
}
function taxRateSeedFromSnapshot(snapshot) {
  return {
    id: snapshot.id,
    organizationId: snapshot.organizationId,
    tenantId: snapshot.tenantId,
    name: snapshot.name,
    code: snapshot.code,
    rate: snapshot.rate,
    countryCode: snapshot.countryCode ?? null,
    regionCode: snapshot.regionCode ?? null,
    postalCode: snapshot.postalCode ?? null,
    city: snapshot.city ?? null,
    customerGroupId: snapshot.customerGroupId ?? null,
    productCategoryId: snapshot.productCategoryId ?? null,
    channelId: snapshot.channelId ?? null,
    priority: snapshot.priority,
    isCompound: snapshot.isCompound,
    isDefault: snapshot.isDefault,
    metadata: snapshot.metadata ? cloneJson(snapshot.metadata) : null,
    startsAt: snapshot.startsAt ? new Date(snapshot.startsAt) : null,
    endsAt: snapshot.endsAt ? new Date(snapshot.endsAt) : null,
    createdAt: /* @__PURE__ */ new Date(),
    updatedAt: /* @__PURE__ */ new Date()
  };
}
async function loadDeliveryWindowSnapshot(em, id) {
  const record = await em.findOne(SalesDeliveryWindow, { id, deletedAt: null });
  if (!record) return null;
  const custom = await loadCustomFieldSnapshot(em, {
    entityId: E.sales.sales_delivery_window,
    recordId: record.id,
    tenantId: record.tenantId,
    organizationId: record.organizationId
  });
  return {
    id: record.id,
    organizationId: record.organizationId,
    tenantId: record.tenantId,
    name: record.name,
    code: record.code,
    description: record.description ?? null,
    leadTimeDays: record.leadTimeDays ?? null,
    cutoffTime: record.cutoffTime ?? null,
    timezone: record.timezone ?? null,
    metadata: record.metadata ? cloneJson(record.metadata) : null,
    isActive: record.isActive,
    custom: Object.keys(custom).length ? custom : null
  };
}
async function loadShippingMethodSnapshot(em, id) {
  const record = await em.findOne(SalesShippingMethod, { id, deletedAt: null });
  if (!record) return null;
  const custom = await loadCustomFieldSnapshot(em, {
    entityId: E.sales.sales_shipping_method,
    recordId: record.id,
    tenantId: record.tenantId,
    organizationId: record.organizationId
  });
  return {
    id: record.id,
    organizationId: record.organizationId,
    tenantId: record.tenantId,
    name: record.name,
    code: record.code,
    description: record.description ?? null,
    carrierCode: record.carrierCode ?? null,
    providerKey: record.providerKey ?? null,
    serviceLevel: record.serviceLevel ?? null,
    estimatedTransitDays: record.estimatedTransitDays ?? null,
    baseRateNet: record.baseRateNet,
    baseRateGross: record.baseRateGross,
    currencyCode: record.currencyCode ?? null,
    metadata: record.metadata ? cloneJson(record.metadata) : null,
    providerSettings: record.metadata && typeof record.metadata === "object" && record.metadata.providerSettings ? cloneJson(record.metadata.providerSettings) : null,
    isActive: record.isActive,
    custom: Object.keys(custom).length ? custom : null
  };
}
async function loadPaymentMethodSnapshot(em, id) {
  const record = await em.findOne(SalesPaymentMethod, { id, deletedAt: null });
  if (!record) return null;
  const custom = await loadCustomFieldSnapshot(em, {
    entityId: E.sales.sales_payment_method,
    recordId: record.id,
    tenantId: record.tenantId,
    organizationId: record.organizationId
  });
  return {
    id: record.id,
    organizationId: record.organizationId,
    tenantId: record.tenantId,
    name: record.name,
    code: record.code,
    description: record.description ?? null,
    providerKey: record.providerKey ?? null,
    terms: record.terms ?? null,
    metadata: record.metadata ? cloneJson(record.metadata) : null,
    providerSettings: record.metadata && typeof record.metadata === "object" && record.metadata.providerSettings ? cloneJson(record.metadata.providerSettings) : null,
    isActive: record.isActive,
    custom: Object.keys(custom).length ? custom : null
  };
}
async function loadTaxRateSnapshot(em, id) {
  const record = await em.findOne(SalesTaxRate, { id, deletedAt: null });
  if (!record) return null;
  const custom = await loadCustomFieldSnapshot(em, {
    entityId: E.sales.sales_tax_rate,
    recordId: record.id,
    tenantId: record.tenantId,
    organizationId: record.organizationId
  });
  return {
    id: record.id,
    organizationId: record.organizationId,
    tenantId: record.tenantId,
    name: record.name,
    code: record.code,
    rate: record.rate,
    countryCode: record.countryCode ?? null,
    regionCode: record.regionCode ?? null,
    postalCode: record.postalCode ?? null,
    city: record.city ?? null,
    customerGroupId: record.customerGroupId ?? null,
    productCategoryId: record.productCategoryId ?? null,
    channelId: record.channelId ?? null,
    priority: record.priority,
    isCompound: record.isCompound,
    isDefault: record.isDefault,
    metadata: record.metadata ? cloneJson(record.metadata) : null,
    startsAt: record.startsAt ? record.startsAt.toISOString() : null,
    endsAt: record.endsAt ? record.endsAt.toISOString() : null,
    custom: Object.keys(custom).length ? custom : null
  };
}
function applyChannelSnapshot(record, snapshot) {
  record.organizationId = snapshot.organizationId;
  record.tenantId = snapshot.tenantId;
  record.name = snapshot.name;
  record.code = snapshot.code ?? null;
  record.description = snapshot.description ?? null;
  record.statusEntryId = snapshot.statusEntryId ?? null;
  record.status = snapshot.status ?? null;
  record.websiteUrl = snapshot.websiteUrl ?? null;
  record.contactEmail = snapshot.contactEmail ?? null;
  record.contactPhone = snapshot.contactPhone ?? null;
  record.addressLine1 = snapshot.addressLine1 ?? null;
  record.addressLine2 = snapshot.addressLine2 ?? null;
  record.city = snapshot.city ?? null;
  record.region = snapshot.region ?? null;
  record.postalCode = snapshot.postalCode ?? null;
  record.country = snapshot.country ?? null;
  record.latitude = snapshot.latitude ?? null;
  record.longitude = snapshot.longitude ?? null;
  record.metadata = snapshot.metadata ? cloneJson(snapshot.metadata) : null;
  record.isActive = snapshot.isActive;
}
function applyDeliveryWindowSnapshot(record, snapshot) {
  record.organizationId = snapshot.organizationId;
  record.tenantId = snapshot.tenantId;
  record.name = snapshot.name;
  record.code = snapshot.code;
  record.description = snapshot.description ?? null;
  record.leadTimeDays = snapshot.leadTimeDays ?? null;
  record.cutoffTime = snapshot.cutoffTime ?? null;
  record.timezone = snapshot.timezone ?? null;
  record.metadata = snapshot.metadata ? cloneJson(snapshot.metadata) : null;
  record.isActive = snapshot.isActive;
}
function applyShippingMethodSnapshot(record, snapshot) {
  record.organizationId = snapshot.organizationId;
  record.tenantId = snapshot.tenantId;
  record.name = snapshot.name;
  record.code = snapshot.code;
  record.description = snapshot.description ?? null;
  record.carrierCode = snapshot.carrierCode ?? null;
  record.providerKey = snapshot.providerKey ?? null;
  record.serviceLevel = snapshot.serviceLevel ?? null;
  record.estimatedTransitDays = snapshot.estimatedTransitDays ?? null;
  record.baseRateNet = snapshot.baseRateNet;
  record.baseRateGross = snapshot.baseRateGross;
  record.currencyCode = snapshot.currencyCode ?? null;
  record.metadata = mergeProviderSettings(snapshot.metadata, snapshot.providerSettings);
  record.isActive = snapshot.isActive;
}
function applyPaymentMethodSnapshot(record, snapshot) {
  record.organizationId = snapshot.organizationId;
  record.tenantId = snapshot.tenantId;
  record.name = snapshot.name;
  record.code = snapshot.code;
  record.description = snapshot.description ?? null;
  record.providerKey = snapshot.providerKey ?? null;
  record.terms = snapshot.terms ?? null;
  record.metadata = mergeProviderSettings(snapshot.metadata, snapshot.providerSettings);
  record.isActive = snapshot.isActive;
}
function applyTaxRateSnapshot(record, snapshot) {
  record.organizationId = snapshot.organizationId;
  record.tenantId = snapshot.tenantId;
  record.name = snapshot.name;
  record.code = snapshot.code;
  record.rate = snapshot.rate;
  record.countryCode = snapshot.countryCode ?? null;
  record.regionCode = snapshot.regionCode ?? null;
  record.postalCode = snapshot.postalCode ?? null;
  record.city = snapshot.city ?? null;
  record.customerGroupId = snapshot.customerGroupId ?? null;
  record.productCategoryId = snapshot.productCategoryId ?? null;
  record.channelId = snapshot.channelId ?? null;
  record.priority = snapshot.priority;
  record.isCompound = snapshot.isCompound;
  record.isDefault = snapshot.isDefault;
  record.metadata = snapshot.metadata ? cloneJson(snapshot.metadata) : null;
  record.startsAt = snapshot.startsAt ? new Date(snapshot.startsAt) : null;
  record.endsAt = snapshot.endsAt ? new Date(snapshot.endsAt) : null;
}
function resolveScopeFromUpdate(entity, patch, ctx) {
  const organizationId = patch.organizationId ?? entity.organizationId;
  const tenantId = patch.tenantId ?? entity.tenantId;
  ensureTenantScope(ctx, tenantId);
  ensureOrganizationScope(ctx, organizationId);
  ensureSameScope(entity, organizationId, tenantId);
  return { organizationId, tenantId };
}
async function deactivateOtherDefaultTaxRates(em, record) {
  await em.nativeUpdate(
    SalesTaxRate,
    {
      organizationId: record.organizationId,
      tenantId: record.tenantId,
      deletedAt: null,
      id: { $ne: record.id }
    },
    { isDefault: false }
  );
}
const createChannelCommand = {
  id: "sales.channels.create",
  async execute(rawInput, ctx) {
    const { parsed, custom } = parseWithCustomFields(channelCreateSchema, rawInput);
    ensureTenantScope(ctx, parsed.tenantId);
    ensureOrganizationScope(ctx, parsed.organizationId);
    const em = ctx.container.resolve("em").fork();
    const statusValue = await resolveDictionaryEntryValue(em, parsed.statusEntryId ?? null, { tenantId: parsed.tenantId });
    const record = em.create(SalesChannel, {
      organizationId: parsed.organizationId,
      tenantId: parsed.tenantId,
      name: parsed.name,
      code: parsed.code ?? null,
      description: parsed.description ?? null,
      statusEntryId: parsed.statusEntryId ?? null,
      status: statusValue,
      websiteUrl: parsed.websiteUrl ?? null,
      contactEmail: parsed.contactEmail ?? null,
      contactPhone: parsed.contactPhone ?? null,
      addressLine1: parsed.addressLine1 ?? null,
      addressLine2: parsed.addressLine2 ?? null,
      city: parsed.city ?? null,
      region: parsed.region ?? null,
      postalCode: parsed.postalCode ?? null,
      country: parsed.country ?? null,
      latitude: toNumericString(parsed.latitude),
      longitude: toNumericString(parsed.longitude),
      metadata: parsed.metadata ? cloneJson(parsed.metadata) : null,
      isActive: parsed.isActive ?? true,
      createdAt: /* @__PURE__ */ new Date(),
      updatedAt: /* @__PURE__ */ new Date()
    });
    em.persist(record);
    await em.flush();
    const dataEngine = ctx.container.resolve("dataEngine");
    await setCustomFieldsIfAny({
      dataEngine,
      entityId: E.sales.sales_channel,
      recordId: record.id,
      organizationId: record.organizationId,
      tenantId: record.tenantId,
      values: custom
    });
    await emitCrudSideEffects({
      dataEngine,
      action: "created",
      entity: record,
      identifiers: {
        id: record.id,
        organizationId: record.organizationId,
        tenantId: record.tenantId
      },
      events: channelCrudEvents,
      indexer: channelCrudIndexer
    });
    return { channelId: record.id };
  },
  captureAfter: async (_input, result, ctx) => {
    const em = ctx.container.resolve("em").fork();
    return loadChannelSnapshot(em, result.channelId);
  },
  buildLog: async ({ result, snapshots }) => {
    const after = snapshots.after;
    if (!after) return null;
    const { translate } = await resolveTranslations();
    return {
      actionLabel: translate("sales.audit.channels.create", "Create sales channel"),
      resourceKind: "sales.channel",
      resourceId: result.channelId,
      tenantId: after.tenantId,
      organizationId: after.organizationId,
      snapshotAfter: after,
      payload: {
        undo: {
          after
        }
      }
    };
  },
  undo: async ({ logEntry, ctx }) => {
    const payload = extractUndoPayload(logEntry);
    const after = payload?.after;
    if (!after) return;
    const em = ctx.container.resolve("em").fork();
    const record = await findOneWithDecryption(em, SalesChannel, { id: after.id }, {}, { tenantId: after.tenantId, organizationId: after.organizationId });
    if (!record) return;
    ensureTenantScope(ctx, record.tenantId);
    ensureOrganizationScope(ctx, record.organizationId);
    em.remove(record);
    await em.flush();
    const dataEngine = ctx.container.resolve("dataEngine");
    const resetValues = buildCustomFieldResetMap(void 0, after.custom ?? void 0);
    if (Object.keys(resetValues).length) {
      await setCustomFieldsIfAny({
        dataEngine,
        entityId: E.sales.sales_channel,
        recordId: after.id,
        organizationId: after.organizationId,
        tenantId: after.tenantId,
        values: resetValues
      });
    }
    await emitCrudUndoSideEffects({
      dataEngine,
      action: "deleted",
      entity: record,
      identifiers: {
        id: record.id,
        organizationId: record.organizationId,
        tenantId: record.tenantId
      },
      events: channelCrudEvents,
      indexer: channelCrudIndexer
    });
  },
  redo: makeCreateRedo({
    entityClass: SalesChannel,
    getSnapshotId: (snapshot) => snapshot.id,
    seedFromSnapshot: channelSeedFromSnapshot,
    findRow: ({ em, id, snapshot }) => findOneWithDecryption(
      em,
      SalesChannel,
      { id },
      void 0,
      { tenantId: snapshot.tenantId, organizationId: snapshot.organizationId }
    ),
    buildResult: (entity) => ({ channelId: entity.id }),
    events: channelCrudEvents,
    indexer: channelCrudIndexer,
    afterRestore: async ({ ctx, snapshot }) => {
      if (snapshot.custom && Object.keys(snapshot.custom).length) {
        await setCustomFieldsIfAny({
          dataEngine: ctx.container.resolve("dataEngine"),
          entityId: E.sales.sales_channel,
          recordId: snapshot.id,
          organizationId: snapshot.organizationId,
          tenantId: snapshot.tenantId,
          values: snapshot.custom
        });
      }
    }
  })
};
const updateChannelCommand = {
  id: "sales.channels.update",
  async prepare(input, ctx) {
    const id = requireId(input, "Channel id is required");
    const em = ctx.container.resolve("em");
    const snapshot = await loadChannelSnapshot(em, id);
    if (snapshot) {
      ensureTenantScope(ctx, snapshot.tenantId);
      ensureOrganizationScope(ctx, snapshot.organizationId);
    }
    return snapshot ? { before: snapshot } : {};
  },
  async execute(rawInput, ctx) {
    const { parsed, custom } = parseWithCustomFields(channelUpdateSchema, rawInput);
    const em = ctx.container.resolve("em").fork();
    const record = await findOneWithDecryption(em, SalesChannel, { id: parsed.id, deletedAt: null }, {}, { tenantId: parsed.tenantId, organizationId: parsed.organizationId });
    if (!record) throw new CrudHttpError(404, { error: "Channel not found" });
    const dataEngine = ctx.container.resolve("dataEngine");
    const scope = resolveScopeFromUpdate(record, parsed, ctx);
    if (parsed.name !== void 0) record.name = parsed.name;
    if (parsed.code !== void 0) record.code = parsed.code ?? null;
    if (parsed.description !== void 0) record.description = parsed.description ?? null;
    if (parsed.statusEntryId !== void 0) {
      record.statusEntryId = parsed.statusEntryId ?? null;
      record.status = await resolveDictionaryEntryValue(em, parsed.statusEntryId ?? null, { tenantId: scope.tenantId });
    }
    if (parsed.websiteUrl !== void 0) record.websiteUrl = parsed.websiteUrl ?? null;
    if (parsed.contactEmail !== void 0) record.contactEmail = parsed.contactEmail ?? null;
    if (parsed.contactPhone !== void 0) record.contactPhone = parsed.contactPhone ?? null;
    if (parsed.addressLine1 !== void 0) record.addressLine1 = parsed.addressLine1 ?? null;
    if (parsed.addressLine2 !== void 0) record.addressLine2 = parsed.addressLine2 ?? null;
    if (parsed.city !== void 0) record.city = parsed.city ?? null;
    if (parsed.region !== void 0) record.region = parsed.region ?? null;
    if (parsed.postalCode !== void 0) record.postalCode = parsed.postalCode ?? null;
    if (parsed.country !== void 0) record.country = parsed.country ?? null;
    if (Object.prototype.hasOwnProperty.call(parsed, "latitude")) {
      record.latitude = toNumericString(parsed.latitude);
    }
    if (Object.prototype.hasOwnProperty.call(parsed, "longitude")) {
      record.longitude = toNumericString(parsed.longitude);
    }
    if (parsed.metadata !== void 0) {
      record.metadata = parsed.metadata ? cloneJson(parsed.metadata) : null;
    }
    if (parsed.isActive !== void 0) record.isActive = parsed.isActive;
    record.organizationId = scope.organizationId;
    record.tenantId = scope.tenantId;
    await em.flush();
    if (custom && Object.keys(custom).length) {
      await setCustomFieldsIfAny({
        dataEngine,
        entityId: E.sales.sales_channel,
        recordId: record.id,
        organizationId: record.organizationId,
        tenantId: record.tenantId,
        values: custom
      });
    }
    await emitCrudSideEffects({
      dataEngine,
      action: "updated",
      entity: record,
      identifiers: {
        id: record.id,
        organizationId: record.organizationId,
        tenantId: record.tenantId
      },
      events: channelCrudEvents,
      indexer: channelCrudIndexer
    });
    return { channelId: record.id };
  },
  captureAfter: async (_input, result, ctx) => {
    const em = ctx.container.resolve("em").fork();
    return loadChannelSnapshot(em, result.channelId);
  },
  buildLog: async ({ snapshots, ctx }) => {
    const before = snapshots.before;
    const after = snapshots.after;
    if (!before || !after) return null;
    const { translate } = await resolveTranslations();
    return {
      actionLabel: translate("sales.audit.channels.update", "Update sales channel"),
      resourceKind: "sales.channel",
      resourceId: before.id,
      tenantId: before.tenantId,
      organizationId: before.organizationId,
      snapshotBefore: before,
      snapshotAfter: after,
      changes: buildChanges(
        before,
        after,
        Object.keys({ ...before ?? {}, ...after ?? {} })
      ),
      payload: {
        undo: {
          before,
          after
        }
      }
    };
  },
  undo: async ({ logEntry, ctx }) => {
    const payload = extractUndoPayload(logEntry);
    const before = payload?.before;
    if (!before) return;
    const em = ctx.container.resolve("em").fork();
    let record = await findOneWithDecryption(em, SalesChannel, { id: before.id }, {}, { tenantId: before.tenantId, organizationId: before.organizationId });
    if (!record) {
      record = em.create(SalesChannel, channelSeedFromSnapshot(before));
      em.persist(record);
    }
    ensureTenantScope(ctx, before.tenantId);
    ensureOrganizationScope(ctx, before.organizationId);
    applyChannelSnapshot(record, before);
    await em.flush();
    const dataEngine = ctx.container.resolve("dataEngine");
    const after = payload?.after;
    const resetValues = buildCustomFieldResetMap(before.custom ?? void 0, after?.custom ?? void 0);
    if (Object.keys(resetValues).length) {
      await setCustomFieldsIfAny({
        dataEngine,
        entityId: E.sales.sales_channel,
        recordId: before.id,
        organizationId: before.organizationId,
        tenantId: before.tenantId,
        values: resetValues
      });
    }
    await emitCrudUndoSideEffects({
      dataEngine,
      action: "updated",
      entity: record,
      identifiers: {
        id: record.id,
        organizationId: record.organizationId,
        tenantId: record.tenantId
      },
      events: channelCrudEvents,
      indexer: channelCrudIndexer
    });
  }
};
const deleteChannelCommand = {
  id: "sales.channels.delete",
  async prepare(input, ctx) {
    const id = requireId(input, "Channel id is required");
    const em = ctx.container.resolve("em");
    const snapshot = await loadChannelSnapshot(em, id);
    if (snapshot) {
      ensureTenantScope(ctx, snapshot.tenantId);
      ensureOrganizationScope(ctx, snapshot.organizationId);
    }
    return snapshot ? { before: snapshot } : {};
  },
  async execute(input, ctx) {
    const id = requireId(input, "Channel id is required");
    const em = ctx.container.resolve("em").fork();
    const record = await findOneWithDecryption(em, SalesChannel, { id }, {});
    if (!record) throw new CrudHttpError(404, { error: "Channel not found" });
    ensureTenantScope(ctx, record.tenantId);
    ensureOrganizationScope(ctx, record.organizationId);
    em.remove(record);
    await em.flush();
    const dataEngine = ctx.container.resolve("dataEngine");
    await emitCrudSideEffects({
      dataEngine,
      action: "deleted",
      entity: record,
      identifiers: {
        id: record.id,
        organizationId: record.organizationId,
        tenantId: record.tenantId
      },
      events: channelCrudEvents,
      indexer: channelCrudIndexer
    });
    return { channelId: id };
  },
  buildLog: async ({ snapshots }) => {
    const before = snapshots.before;
    if (!before) return null;
    const { translate } = await resolveTranslations();
    return {
      actionLabel: translate("sales.audit.channels.delete", "Delete sales channel"),
      resourceKind: "sales.channel",
      resourceId: before.id,
      tenantId: before.tenantId,
      organizationId: before.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 record = await findOneWithDecryption(em, SalesChannel, { id: before.id }, {}, { tenantId: before.tenantId, organizationId: before.organizationId });
    if (!record) {
      record = em.create(SalesChannel, channelSeedFromSnapshot(before));
      em.persist(record);
    }
    ensureTenantScope(ctx, before.tenantId);
    ensureOrganizationScope(ctx, before.organizationId);
    applyChannelSnapshot(record, before);
    await em.flush();
    const dataEngine = ctx.container.resolve("dataEngine");
    if (before.custom && Object.keys(before.custom).length) {
      await setCustomFieldsIfAny({
        dataEngine,
        entityId: E.sales.sales_channel,
        recordId: before.id,
        organizationId: before.organizationId,
        tenantId: before.tenantId,
        values: before.custom
      });
    }
    await emitCrudUndoSideEffects({
      dataEngine,
      action: "created",
      entity: record,
      identifiers: {
        id: record.id,
        organizationId: record.organizationId,
        tenantId: record.tenantId
      },
      events: channelCrudEvents,
      indexer: channelCrudIndexer
    });
  }
};
const createDeliveryWindowCommand = {
  id: "sales.delivery-windows.create",
  async execute(rawInput, ctx) {
    const { parsed, custom } = parseWithCustomFields(deliveryWindowCreateSchema, rawInput);
    ensureTenantScope(ctx, parsed.tenantId);
    ensureOrganizationScope(ctx, parsed.organizationId);
    const em = ctx.container.resolve("em").fork();
    const record = em.create(SalesDeliveryWindow, {
      organizationId: parsed.organizationId,
      tenantId: parsed.tenantId,
      name: parsed.name,
      code: parsed.code,
      description: parsed.description ?? null,
      leadTimeDays: parsed.leadTimeDays ?? null,
      cutoffTime: parsed.cutoffTime ?? null,
      timezone: parsed.timezone ?? null,
      metadata: parsed.metadata ? cloneJson(parsed.metadata) : null,
      isActive: parsed.isActive ?? true,
      createdAt: /* @__PURE__ */ new Date(),
      updatedAt: /* @__PURE__ */ new Date()
    });
    em.persist(record);
    await em.flush();
    await setCustomFieldsIfAny({
      dataEngine: ctx.container.resolve("dataEngine"),
      entityId: E.sales.sales_delivery_window,
      recordId: record.id,
      organizationId: record.organizationId,
      tenantId: record.tenantId,
      values: custom
    });
    return { deliveryWindowId: record.id };
  },
  captureAfter: async (_input, result, ctx) => {
    const em = ctx.container.resolve("em").fork();
    return loadDeliveryWindowSnapshot(em, result.deliveryWindowId);
  },
  buildLog: async ({ result, snapshots }) => {
    const after = snapshots.after;
    if (!after) return null;
    const { translate } = await resolveTranslations();
    return {
      actionLabel: translate("sales.audit.delivery-windows.create", "Create delivery window"),
      resourceKind: "sales.delivery-window",
      resourceId: result.deliveryWindowId,
      tenantId: after.tenantId,
      organizationId: after.organizationId,
      snapshotAfter: after,
      payload: {
        undo: {
          after
        }
      }
    };
  },
  undo: async ({ logEntry, ctx }) => {
    const payload = extractUndoPayload(logEntry);
    const after = payload?.after;
    if (!after) return;
    const em = ctx.container.resolve("em").fork();
    const record = await em.findOne(SalesDeliveryWindow, { id: after.id });
    if (!record) return;
    ensureTenantScope(ctx, record.tenantId);
    ensureOrganizationScope(ctx, record.organizationId);
    em.remove(record);
    await em.flush();
    const resetValues = buildCustomFieldResetMap(void 0, after.custom ?? void 0);
    if (Object.keys(resetValues).length) {
      await setCustomFieldsIfAny({
        dataEngine: ctx.container.resolve("dataEngine"),
        entityId: E.sales.sales_delivery_window,
        recordId: after.id,
        organizationId: after.organizationId,
        tenantId: after.tenantId,
        values: resetValues
      });
    }
  },
  redo: makeCreateRedo({
    entityClass: SalesDeliveryWindow,
    getSnapshotId: (snapshot) => snapshot.id,
    seedFromSnapshot: deliveryWindowSeedFromSnapshot,
    buildResult: (entity) => ({ deliveryWindowId: entity.id }),
    afterRestore: async ({ ctx, snapshot }) => {
      if (snapshot.custom && Object.keys(snapshot.custom).length) {
        await setCustomFieldsIfAny({
          dataEngine: ctx.container.resolve("dataEngine"),
          entityId: E.sales.sales_delivery_window,
          recordId: snapshot.id,
          organizationId: snapshot.organizationId,
          tenantId: snapshot.tenantId,
          values: snapshot.custom
        });
      }
    }
  })
};
const updateDeliveryWindowCommand = {
  id: "sales.delivery-windows.update",
  async prepare(input, ctx) {
    const id = requireId(input, "Delivery window id is required");
    const em = ctx.container.resolve("em");
    const snapshot = await loadDeliveryWindowSnapshot(em, id);
    if (snapshot) {
      ensureTenantScope(ctx, snapshot.tenantId);
      ensureOrganizationScope(ctx, snapshot.organizationId);
    }
    return snapshot ? { before: snapshot } : {};
  },
  async execute(rawInput, ctx) {
    const { parsed, custom } = parseWithCustomFields(deliveryWindowUpdateSchema, rawInput);
    const em = ctx.container.resolve("em").fork();
    const record = await em.findOne(SalesDeliveryWindow, { id: parsed.id, deletedAt: null });
    if (!record) throw new CrudHttpError(404, { error: "Delivery window not found" });
    const scope = resolveScopeFromUpdate(record, parsed, ctx);
    record.organizationId = scope.organizationId;
    record.tenantId = scope.tenantId;
    if (parsed.name !== void 0) record.name = parsed.name;
    if (parsed.code !== void 0) record.code = parsed.code;
    if (parsed.description !== void 0) record.description = parsed.description ?? null;
    if (parsed.leadTimeDays !== void 0) record.leadTimeDays = parsed.leadTimeDays ?? null;
    if (parsed.cutoffTime !== void 0) record.cutoffTime = parsed.cutoffTime ?? null;
    if (parsed.timezone !== void 0) record.timezone = parsed.timezone ?? null;
    if (parsed.metadata !== void 0) {
      record.metadata = parsed.metadata ? cloneJson(parsed.metadata) : null;
    }
    if (parsed.isActive !== void 0) record.isActive = parsed.isActive;
    await em.flush();
    if (custom && Object.keys(custom).length) {
      await setCustomFieldsIfAny({
        dataEngine: ctx.container.resolve("dataEngine"),
        entityId: E.sales.sales_delivery_window,
        recordId: record.id,
        organizationId: record.organizationId,
        tenantId: record.tenantId,
        values: custom
      });
    }
    return { deliveryWindowId: record.id };
  },
  captureAfter: async (_input, result, ctx) => {
    const em = ctx.container.resolve("em").fork();
    return loadDeliveryWindowSnapshot(em, result.deliveryWindowId);
  },
  buildLog: async ({ snapshots }) => {
    const before = snapshots.before;
    const after = snapshots.after;
    if (!before || !after) return null;
    const { translate } = await resolveTranslations();
    return {
      actionLabel: translate("sales.audit.delivery-windows.update", "Update delivery window"),
      resourceKind: "sales.delivery-window",
      resourceId: before.id,
      tenantId: before.tenantId,
      organizationId: before.organizationId,
      snapshotBefore: before,
      snapshotAfter: after,
      changes: buildChanges(
        before,
        after,
        Object.keys({ ...before ?? {}, ...after ?? {} })
      ),
      payload: {
        undo: {
          before,
          after
        }
      }
    };
  },
  undo: async ({ logEntry, ctx }) => {
    const payload = extractUndoPayload(logEntry);
    const before = payload?.before;
    if (!before) return;
    const em = ctx.container.resolve("em").fork();
    let record = await em.findOne(SalesDeliveryWindow, { id: before.id });
    if (!record) {
      record = em.create(SalesDeliveryWindow, deliveryWindowSeedFromSnapshot(before));
      em.persist(record);
    }
    ensureTenantScope(ctx, before.tenantId);
    ensureOrganizationScope(ctx, before.organizationId);
    applyDeliveryWindowSnapshot(record, before);
    await em.flush();
    const resetValues = buildCustomFieldResetMap(before.custom ?? void 0, payload?.after?.custom ?? void 0);
    if (Object.keys(resetValues).length) {
      await setCustomFieldsIfAny({
        dataEngine: ctx.container.resolve("dataEngine"),
        entityId: E.sales.sales_delivery_window,
        recordId: before.id,
        organizationId: before.organizationId,
        tenantId: before.tenantId,
        values: resetValues
      });
    }
  }
};
const deleteDeliveryWindowCommand = {
  id: "sales.delivery-windows.delete",
  async prepare(input, ctx) {
    const id = requireId(input, "Delivery window id is required");
    const em = ctx.container.resolve("em");
    const snapshot = await loadDeliveryWindowSnapshot(em, id);
    if (snapshot) {
      ensureTenantScope(ctx, snapshot.tenantId);
      ensureOrganizationScope(ctx, snapshot.organizationId);
    }
    return snapshot ? { before: snapshot } : {};
  },
  async execute(input, ctx) {
    const id = requireId(input, "Delivery window id is required");
    const em = ctx.container.resolve("em").fork();
    const record = await em.findOne(SalesDeliveryWindow, { id });
    if (!record) throw new CrudHttpError(404, { error: "Delivery window not found" });
    ensureTenantScope(ctx, record.tenantId);
    ensureOrganizationScope(ctx, record.organizationId);
    em.remove(record);
    await em.flush();
    return { deliveryWindowId: id };
  },
  buildLog: async ({ snapshots }) => {
    const before = snapshots.before;
    if (!before) return null;
    const { translate } = await resolveTranslations();
    return {
      actionLabel: translate("sales.audit.delivery-windows.delete", "Delete delivery window"),
      resourceKind: "sales.delivery-window",
      resourceId: before.id,
      tenantId: before.tenantId,
      organizationId: before.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 record = await em.findOne(SalesDeliveryWindow, { id: before.id });
    if (!record) {
      record = em.create(SalesDeliveryWindow, deliveryWindowSeedFromSnapshot(before));
      em.persist(record);
    }
    ensureTenantScope(ctx, before.tenantId);
    ensureOrganizationScope(ctx, before.organizationId);
    applyDeliveryWindowSnapshot(record, before);
    await em.flush();
    if (before.custom && Object.keys(before.custom).length) {
      await setCustomFieldsIfAny({
        dataEngine: ctx.container.resolve("dataEngine"),
        entityId: E.sales.sales_delivery_window,
        recordId: before.id,
        organizationId: before.organizationId,
        tenantId: before.tenantId,
        values: before.custom
      });
    }
  }
};
const createShippingMethodCommand = {
  id: "sales.shipping-methods.create",
  async execute(rawInput, ctx) {
    const { parsed, custom } = parseWithCustomFields(shippingMethodCreateSchema, rawInput);
    ensureTenantScope(ctx, parsed.tenantId);
    ensureOrganizationScope(ctx, parsed.organizationId);
    const em = ctx.container.resolve("em").fork();
    const record = em.create(SalesShippingMethod, {
      organizationId: parsed.organizationId,
      tenantId: parsed.tenantId,
      name: parsed.name,
      code: parsed.code,
      description: parsed.description ?? null,
      carrierCode: parsed.carrierCode ?? null,
      providerKey: parsed.providerKey ?? null,
      serviceLevel: parsed.serviceLevel ?? null,
      estimatedTransitDays: parsed.estimatedTransitDays ?? null,
      baseRateNet: toNumericString(parsed.baseRateNet) ?? "0",
      baseRateGross: toNumericString(parsed.baseRateGross) ?? "0",
      currencyCode: parsed.currencyCode ?? null,
      metadata: mergeProviderSettings(parsed.metadata, parsed.providerSettings),
      isActive: parsed.isActive ?? true,
      createdAt: /* @__PURE__ */ new Date(),
      updatedAt: /* @__PURE__ */ new Date()
    });
    em.persist(record);
    await em.flush();
    await setCustomFieldsIfAny({
      dataEngine: ctx.container.resolve("dataEngine"),
      entityId: E.sales.sales_shipping_method,
      recordId: record.id,
      organizationId: record.organizationId,
      tenantId: record.tenantId,
      values: custom
    });
    return { shippingMethodId: record.id };
  },
  captureAfter: async (_input, result, ctx) => {
    const em = ctx.container.resolve("em").fork();
    return loadShippingMethodSnapshot(em, result.shippingMethodId);
  },
  buildLog: async ({ result, snapshots }) => {
    const after = snapshots.after;
    if (!after) return null;
    const { translate } = await resolveTranslations();
    return {
      actionLabel: translate("sales.audit.shipping-methods.create", "Create shipping method"),
      resourceKind: "sales.shipping-method",
      resourceId: result.shippingMethodId,
      tenantId: after.tenantId,
      organizationId: after.organizationId,
      snapshotAfter: after,
      payload: {
        undo: {
          after
        }
      }
    };
  },
  undo: async ({ logEntry, ctx }) => {
    const payload = extractUndoPayload(logEntry);
    const after = payload?.after;
    if (!after) return;
    const em = ctx.container.resolve("em").fork();
    const record = await em.findOne(SalesShippingMethod, { id: after.id });
    if (!record) return;
    ensureTenantScope(ctx, record.tenantId);
    ensureOrganizationScope(ctx, record.organizationId);
    em.remove(record);
    await em.flush();
    const resetValues = buildCustomFieldResetMap(void 0, after.custom ?? void 0);
    if (Object.keys(resetValues).length) {
      await setCustomFieldsIfAny({
        dataEngine: ctx.container.resolve("dataEngine"),
        entityId: E.sales.sales_shipping_method,
        recordId: after.id,
        organizationId: after.organizationId,
        tenantId: after.tenantId,
        values: resetValues
      });
    }
  },
  redo: makeCreateRedo({
    entityClass: SalesShippingMethod,
    getSnapshotId: (snapshot) => snapshot.id,
    seedFromSnapshot: shippingMethodSeedFromSnapshot,
    buildResult: (entity) => ({ shippingMethodId: entity.id }),
    afterRestore: async ({ ctx, snapshot }) => {
      if (snapshot.custom && Object.keys(snapshot.custom).length) {
        await setCustomFieldsIfAny({
          dataEngine: ctx.container.resolve("dataEngine"),
          entityId: E.sales.sales_shipping_method,
          recordId: snapshot.id,
          organizationId: snapshot.organizationId,
          tenantId: snapshot.tenantId,
          values: snapshot.custom
        });
      }
    }
  })
};
const updateShippingMethodCommand = {
  id: "sales.shipping-methods.update",
  async prepare(input, ctx) {
    const id = requireId(input, "Shipping method id is required");
    const em = ctx.container.resolve("em");
    const snapshot = await loadShippingMethodSnapshot(em, id);
    if (snapshot) {
      ensureTenantScope(ctx, snapshot.tenantId);
      ensureOrganizationScope(ctx, snapshot.organizationId);
    }
    return snapshot ? { before: snapshot } : {};
  },
  async execute(rawInput, ctx) {
    const { parsed, custom } = parseWithCustomFields(shippingMethodUpdateSchema, rawInput);
    const em = ctx.container.resolve("em").fork();
    const record = await em.findOne(SalesShippingMethod, { id: parsed.id, deletedAt: null });
    if (!record) throw new CrudHttpError(404, { error: "Shipping method not found" });
    const scope = resolveScopeFromUpdate(record, parsed, ctx);
    record.organizationId = scope.organizationId;
    record.tenantId = scope.tenantId;
    if (parsed.name !== void 0) record.name = parsed.name;
    if (parsed.code !== void 0) record.code = parsed.code;
    if (parsed.description !== void 0) record.description = parsed.description ?? null;
    if (parsed.carrierCode !== void 0) record.carrierCode = parsed.carrierCode ?? null;
    if (parsed.providerKey !== void 0) record.providerKey = parsed.providerKey ?? null;
    if (parsed.serviceLevel !== void 0) record.serviceLevel = parsed.serviceLevel ?? null;
    if (parsed.estimatedTransitDays !== void 0) {
      record.estimatedTransitDays = parsed.estimatedTransitDays ?? null;
    }
    if (Object.prototype.hasOwnProperty.call(parsed, "baseRateNet")) {
      record.baseRateNet = toNumericString(parsed.baseRateNet) ?? "0";
    }
    if (Object.prototype.hasOwnProperty.call(parsed, "baseRateGross")) {
      record.baseRateGross = toNumericString(parsed.baseRateGross) ?? "0";
    }
    if (parsed.currencyCode !== void 0) record.currencyCode = parsed.currencyCode ?? null;
    if (parsed.metadata !== void 0 || parsed.providerSettings !== void 0) {
      const baseMeta = parsed.metadata !== void 0 ? parsed.metadata ? cloneJson(parsed.metadata) : null : record.metadata;
      const settings = parsed.providerSettings !== void 0 ? parsed.providerSettings ?? null : readProviderSettings(record.metadata);
      record.metadata = mergeProviderSettings(baseMeta, settings);
    }
    if (parsed.isActive !== void 0) record.isActive = parsed.isActive;
    await em.flush();
    if (custom && Object.keys(custom).length) {
      await setCustomFieldsIfAny({
        dataEngine: ctx.container.resolve("dataEngine"),
        entityId: E.sales.sales_shipping_method,
        recordId: record.id,
        organizationId: record.organizationId,
        tenantId: record.tenantId,
        values: custom
      });
    }
    return { shippingMethodId: record.id };
  },
  captureAfter: async (_input, result, ctx) => {
    const em = ctx.container.resolve("em").fork();
    return loadShippingMethodSnapshot(em, result.shippingMethodId);
  },
  buildLog: async ({ snapshots }) => {
    const before = snapshots.before;
    const after = snapshots.after;
    if (!before || !after) return null;
    const { translate } = await resolveTranslations();
    return {
      actionLabel: translate("sales.audit.shipping-methods.update", "Update shipping method"),
      resourceKind: "sales.shipping-method",
      resourceId: before.id,
      tenantId: before.tenantId,
      organizationId: before.organizationId,
      snapshotBefore: before,
      snapshotAfter: after,
      changes: buildChanges(
        before,
        after,
        Object.keys({ ...before ?? {}, ...after ?? {} })
      ),
      payload: {
        undo: {
          before,
          after
        }
      }
    };
  },
  undo: async ({ logEntry, ctx }) => {
    const payload = extractUndoPayload(logEntry);
    const before = payload?.before;
    if (!before) return;
    const em = ctx.container.resolve("em").fork();
    let record = await em.findOne(SalesShippingMethod, { id: before.id });
    if (!record) {
      record = em.create(SalesShippingMethod, shippingMethodSeedFromSnapshot(before));
      em.persist(record);
    }
    ensureTenantScope(ctx, before.tenantId);
    ensureOrganizationScope(ctx, before.organizationId);
    applyShippingMethodSnapshot(record, before);
    await em.flush();
    const resetValues = buildCustomFieldResetMap(before.custom ?? void 0, payload?.after?.custom ?? void 0);
    if (Object.keys(resetValues).length) {
      await setCustomFieldsIfAny({
        dataEngine: ctx.container.resolve("dataEngine"),
        entityId: E.sales.sales_shipping_method,
        recordId: before.id,
        organizationId: before.organizationId,
        tenantId: before.tenantId,
        values: resetValues
      });
    }
  }
};
const deleteShippingMethodCommand = {
  id: "sales.shipping-methods.delete",
  async prepare(input, ctx) {
    const id = requireId(input, "Shipping method id is required");
    const em = ctx.container.resolve("em");
    const snapshot = await loadShippingMethodSnapshot(em, id);
    if (snapshot) {
      ensureTenantScope(ctx, snapshot.tenantId);
      ensureOrganizationScope(ctx, snapshot.organizationId);
    }
    return snapshot ? { before: snapshot } : {};
  },
  async execute(input, ctx) {
    const id = requireId(input, "Shipping method id is required");
    const em = ctx.container.resolve("em").fork();
    const record = await em.findOne(SalesShippingMethod, { id });
    if (!record) throw new CrudHttpError(404, { error: "Shipping method not found" });
    ensureTenantScope(ctx, record.tenantId);
    ensureOrganizationScope(ctx, record.organizationId);
    em.remove(record);
    await em.flush();
    return { shippingMethodId: id };
  },
  buildLog: async ({ snapshots }) => {
    const before = snapshots.before;
    if (!before) return null;
    const { translate } = await resolveTranslations();
    return {
      actionLabel: translate("sales.audit.shipping-methods.delete", "Delete shipping method"),
      resourceKind: "sales.shipping-method",
      resourceId: before.id,
      tenantId: before.tenantId,
      organizationId: before.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 record = await em.findOne(SalesShippingMethod, { id: before.id });
    if (!record) {
      record = em.create(SalesShippingMethod, shippingMethodSeedFromSnapshot(before));
      em.persist(record);
    }
    ensureTenantScope(ctx, before.tenantId);
    ensureOrganizationScope(ctx, before.organizationId);
    applyShippingMethodSnapshot(record, before);
    await em.flush();
    if (before.custom && Object.keys(before.custom).length) {
      await setCustomFieldsIfAny({
        dataEngine: ctx.container.resolve("dataEngine"),
        entityId: E.sales.sales_shipping_method,
        recordId: before.id,
        organizationId: before.organizationId,
        tenantId: before.tenantId,
        values: before.custom
      });
    }
  }
};
const createPaymentMethodCommand = {
  id: "sales.payment-methods.create",
  async execute(rawInput, ctx) {
    const { parsed, custom } = parseWithCustomFields(paymentMethodCreateSchema, rawInput);
    ensureTenantScope(ctx, parsed.tenantId);
    ensureOrganizationScope(ctx, parsed.organizationId);
    const em = ctx.container.resolve("em").fork();
    const record = em.create(SalesPaymentMethod, {
      organizationId: parsed.organizationId,
      tenantId: parsed.tenantId,
      name: parsed.name,
      code: parsed.code,
      description: parsed.description ?? null,
      providerKey: parsed.providerKey ?? null,
      terms: parsed.terms ?? null,
      metadata: mergeProviderSettings(parsed.metadata, parsed.providerSettings),
      isActive: parsed.isActive ?? true,
      createdAt: /* @__PURE__ */ new Date(),
      updatedAt: /* @__PURE__ */ new Date()
    });
    em.persist(record);
    await em.flush();
    await setCustomFieldsIfAny({
      dataEngine: ctx.container.resolve("dataEngine"),
      entityId: E.sales.sales_payment_method,
      recordId: record.id,
      organizationId: record.organizationId,
      tenantId: record.tenantId,
      values: custom
    });
    return { paymentMethodId: record.id };
  },
  captureAfter: async (_input, result, ctx) => {
    const em = ctx.container.resolve("em").fork();
    return loadPaymentMethodSnapshot(em, result.paymentMethodId);
  },
  buildLog: async ({ result, snapshots }) => {
    const after = snapshots.after;
    if (!after) return null;
    const { translate } = await resolveTranslations();
    return {
      actionLabel: translate("sales.audit.payment-methods.create", "Create payment method"),
      resourceKind: "sales.payment-method",
      resourceId: result.paymentMethodId,
      tenantId: after.tenantId,
      organizationId: after.organizationId,
      snapshotAfter: after,
      payload: {
        undo: {
          after
        }
      }
    };
  },
  undo: async ({ logEntry, ctx }) => {
    const payload = extractUndoPayload(logEntry);
    const after = payload?.after;
    if (!after) return;
    const em = ctx.container.resolve("em").fork();
    const record = await em.findOne(SalesPaymentMethod, { id: after.id });
    if (!record) return;
    ensureTenantScope(ctx, record.tenantId);
    ensureOrganizationScope(ctx, record.organizationId);
    em.remove(record);
    await em.flush();
    const resetValues = buildCustomFieldResetMap(void 0, after.custom ?? void 0);
    if (Object.keys(resetValues).length) {
      await setCustomFieldsIfAny({
        dataEngine: ctx.container.resolve("dataEngine"),
        entityId: E.sales.sales_payment_method,
        recordId: after.id,
        organizationId: after.organizationId,
        tenantId: after.tenantId,
        values: resetValues
      });
    }
  },
  redo: makeCreateRedo({
    entityClass: SalesPaymentMethod,
    getSnapshotId: (snapshot) => snapshot.id,
    seedFromSnapshot: paymentMethodSeedFromSnapshot,
    buildResult: (entity) => ({ paymentMethodId: entity.id }),
    afterRestore: async ({ ctx, snapshot }) => {
      if (snapshot.custom && Object.keys(snapshot.custom).length) {
        await setCustomFieldsIfAny({
          dataEngine: ctx.container.resolve("dataEngine"),
          entityId: E.sales.sales_payment_method,
          recordId: snapshot.id,
          organizationId: snapshot.organizationId,
          tenantId: snapshot.tenantId,
          values: snapshot.custom
        });
      }
    }
  })
};
const updatePaymentMethodCommand = {
  id: "sales.payment-methods.update",
  async prepare(input, ctx) {
    const id = requireId(input, "Payment method id is required");
    const em = ctx.container.resolve("em");
    const snapshot = await loadPaymentMethodSnapshot(em, id);
    if (snapshot) {
      ensureTenantScope(ctx, snapshot.tenantId);
      ensureOrganizationScope(ctx, snapshot.organizationId);
    }
    return snapshot ? { before: snapshot } : {};
  },
  async execute(rawInput, ctx) {
    const { parsed, custom } = parseWithCustomFields(paymentMethodUpdateSchema, rawInput);
    const em = ctx.container.resolve("em").fork();
    const record = await em.findOne(SalesPaymentMethod, { id: parsed.id, deletedAt: null });
    if (!record) throw new CrudHttpError(404, { error: "Payment method not found" });
    const scope = resolveScopeFromUpdate(record, parsed, ctx);
    record.organizationId = scope.organizationId;
    record.tenantId = scope.tenantId;
    if (parsed.name !== void 0) record.name = parsed.name;
    if (parsed.code !== void 0) record.code = parsed.code;
    if (parsed.description !== void 0) record.description = parsed.description ?? null;
    if (parsed.providerKey !== void 0) record.providerKey = parsed.providerKey ?? null;
    if (parsed.terms !== void 0) record.terms = parsed.terms ?? null;
    if (parsed.metadata !== void 0 || parsed.providerSettings !== void 0) {
      const baseMeta = parsed.metadata !== void 0 ? parsed.metadata ? cloneJson(parsed.metadata) : null : record.metadata;
      const settings = parsed.providerSettings !== void 0 ? parsed.providerSettings ?? null : readProviderSettings(record.metadata);
      record.metadata = mergeProviderSettings(baseMeta, settings);
    }
    if (parsed.isActive !== void 0) record.isActive = parsed.isActive;
    await em.flush();
    if (custom && Object.keys(custom).length) {
      await setCustomFieldsIfAny({
        dataEngine: ctx.container.resolve("dataEngine"),
        entityId: E.sales.sales_payment_method,
        recordId: record.id,
        organizationId: record.organizationId,
        tenantId: record.tenantId,
        values: custom
      });
    }
    return { paymentMethodId: record.id };
  },
  captureAfter: async (_input, result, ctx) => {
    const em = ctx.container.resolve("em").fork();
    return loadPaymentMethodSnapshot(em, result.paymentMethodId);
  },
  buildLog: async ({ snapshots }) => {
    const before = snapshots.before;
    const after = snapshots.after;
    if (!before || !after) return null;
    const { translate } = await resolveTranslations();
    return {
      actionLabel: translate("sales.audit.payment-methods.update", "Update payment method"),
      resourceKind: "sales.payment-method",
      resourceId: before.id,
      tenantId: before.tenantId,
      organizationId: before.organizationId,
      snapshotBefore: before,
      snapshotAfter: after,
      changes: buildChanges(
        before,
        after,
        Object.keys({ ...before ?? {}, ...after ?? {} })
      ),
      payload: {
        undo: {
          before,
          after
        }
      }
    };
  },
  undo: async ({ logEntry, ctx }) => {
    const payload = extractUndoPayload(logEntry);
    const before = payload?.before;
    if (!before) return;
    const em = ctx.container.resolve("em").fork();
    let record = await em.findOne(SalesPaymentMethod, { id: before.id });
    if (!record) {
      record = em.create(SalesPaymentMethod, paymentMethodSeedFromSnapshot(before));
      em.persist(record);
    }
    ensureTenantScope(ctx, before.tenantId);
    ensureOrganizationScope(ctx, before.organizationId);
    applyPaymentMethodSnapshot(record, before);
    await em.flush();
    const resetValues = buildCustomFieldResetMap(before.custom ?? void 0, payload?.after?.custom ?? void 0);
    if (Object.keys(resetValues).length) {
      await setCustomFieldsIfAny({
        dataEngine: ctx.container.resolve("dataEngine"),
        entityId: E.sales.sales_payment_method,
        recordId: before.id,
        organizationId: before.organizationId,
        tenantId: before.tenantId,
        values: resetValues
      });
    }
  }
};
const deletePaymentMethodCommand = {
  id: "sales.payment-methods.delete",
  async prepare(input, ctx) {
    const id = requireId(input, "Payment method id is required");
    const em = ctx.container.resolve("em");
    const snapshot = await loadPaymentMethodSnapshot(em, id);
    if (snapshot) {
      ensureTenantScope(ctx, snapshot.tenantId);
      ensureOrganizationScope(ctx, snapshot.organizationId);
    }
    return snapshot ? { before: snapshot } : {};
  },
  async execute(input, ctx) {
    const id = requireId(input, "Payment method id is required");
    const em = ctx.container.resolve("em").fork();
    const record = await em.findOne(SalesPaymentMethod, { id });
    if (!record) throw new CrudHttpError(404, { error: "Payment method not found" });
    ensureTenantScope(ctx, record.tenantId);
    ensureOrganizationScope(ctx, record.organizationId);
    em.remove(record);
    await em.flush();
    return { paymentMethodId: id };
  },
  buildLog: async ({ snapshots }) => {
    const before = snapshots.before;
    if (!before) return null;
    const { translate } = await resolveTranslations();
    return {
      actionLabel: translate("sales.audit.payment-methods.delete", "Delete payment method"),
      resourceKind: "sales.payment-method",
      resourceId: before.id,
      tenantId: before.tenantId,
      organizationId: before.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 record = await em.findOne(SalesPaymentMethod, { id: before.id });
    if (!record) {
      record = em.create(SalesPaymentMethod, paymentMethodSeedFromSnapshot(before));
      em.persist(record);
    }
    ensureTenantScope(ctx, before.tenantId);
    ensureOrganizationScope(ctx, before.organizationId);
    applyPaymentMethodSnapshot(record, before);
    await em.flush();
    if (before.custom && Object.keys(before.custom).length) {
      await setCustomFieldsIfAny({
        dataEngine: ctx.container.resolve("dataEngine"),
        entityId: E.sales.sales_payment_method,
        recordId: before.id,
        organizationId: before.organizationId,
        tenantId: before.tenantId,
        values: before.custom
      });
    }
  }
};
const createTaxRateCommand = {
  id: "sales.tax-rates.create",
  async execute(rawInput, ctx) {
    const { parsed, custom } = parseWithCustomFields(taxRateCreateSchema, rawInput);
    ensureTenantScope(ctx, parsed.tenantId);
    ensureOrganizationScope(ctx, parsed.organizationId);
    const em = ctx.container.resolve("em").fork();
    if (parsed.channelId) {
      const channel = await findOneWithDecryption(em, SalesChannel, { id: parsed.channelId, deletedAt: null }, {}, { tenantId: parsed.tenantId, organizationId: parsed.organizationId });
      const channelInScope = assertFound(channel, "Channel not found for tax rate");
      ensureSameScope(channelInScope, parsed.organizationId, parsed.tenantId);
    }
    const record = em.create(SalesTaxRate, {
      organizationId: parsed.organizationId,
      tenantId: parsed.tenantId,
      name: parsed.name,
      code: parsed.code,
      rate: toNumericString(parsed.rate) ?? "0",
      countryCode: parsed.countryCode ?? null,
      regionCode: parsed.regionCode ?? null,
      postalCode: parsed.postalCode ?? null,
      city: parsed.city ?? null,
      customerGroupId: parsed.customerGroupId ?? null,
      productCategoryId: parsed.productCategoryId ?? null,
      channelId: parsed.channelId ?? null,
      priority: parsed.priority ?? 0,
      isCompound: parsed.isCompound ?? false,
      isDefault: parsed.isDefault ?? false,
      metadata: parsed.metadata ? cloneJson(parsed.metadata) : null,
      startsAt: parsed.startsAt ?? null,
      endsAt: parsed.endsAt ?? null,
      createdAt: /* @__PURE__ */ new Date(),
      updatedAt: /* @__PURE__ */ new Date()
    });
    em.persist(record);
    await em.flush();
    if (record.isDefault) {
      await deactivateOtherDefaultTaxRates(em, record);
    }
    await setCustomFieldsIfAny({
      dataEngine: ctx.container.resolve("dataEngine"),
      entityId: E.sales.sales_tax_rate,
      recordId: record.id,
      organizationId: record.organizationId,
      tenantId: record.tenantId,
      values: custom
    });
    return { taxRateId: record.id };
  },
  captureAfter: async (_input, result, ctx) => {
    const em = ctx.container.resolve("em").fork();
    return loadTaxRateSnapshot(em, result.taxRateId);
  },
  buildLog: async ({ result, snapshots }) => {
    const after = snapshots.after;
    if (!after) return null;
    const { translate } = await resolveTranslations();
    return {
      actionLabel: translate("sales.audit.tax-rates.create", "Create tax rate"),
      resourceKind: "sales.tax-rate",
      resourceId: result.taxRateId,
      tenantId: after.tenantId,
      organizationId: after.organizationId,
      snapshotAfter: after,
      payload: {
        undo: {
          after
        }
      }
    };
  },
  undo: async ({ logEntry, ctx }) => {
    const payload = extractUndoPayload(logEntry);
    const after = payload?.after;
    if (!after) return;
    const em = ctx.container.resolve("em").fork();
    const record = await em.findOne(SalesTaxRate, { id: after.id });
    if (!record) return;
    ensureTenantScope(ctx, record.tenantId);
    ensureOrganizationScope(ctx, record.organizationId);
    em.remove(record);
    await em.flush();
    const resetValues = buildCustomFieldResetMap(void 0, after.custom ?? void 0);
    if (Object.keys(resetValues).length) {
      await setCustomFieldsIfAny({
        dataEngine: ctx.container.resolve("dataEngine"),
        entityId: E.sales.sales_tax_rate,
        recordId: after.id,
        organizationId: after.organizationId,
        tenantId: after.tenantId,
        values: resetValues
      });
    }
  },
  redo: makeCreateRedo({
    entityClass: SalesTaxRate,
    getSnapshotId: (snapshot) => snapshot.id,
    seedFromSnapshot: taxRateSeedFromSnapshot,
    buildResult: (entity) => ({ taxRateId: entity.id }),
    afterRestore: async ({ em, ctx, entity, snapshot }) => {
      if (entity.isDefault) {
        await deactivateOtherDefaultTaxRates(em, entity);
        await em.flush();
      }
      if (snapshot.custom && Object.keys(snapshot.custom).length) {
        await setCustomFieldsIfAny({
          dataEngine: ctx.container.resolve("dataEngine"),
          entityId: E.sales.sales_tax_rate,
          recordId: snapshot.id,
          organizationId: snapshot.organizationId,
          tenantId: snapshot.tenantId,
          values: snapshot.custom
        });
      }
    }
  })
};
const updateTaxRateCommand = {
  id: "sales.tax-rates.update",
  async prepare(input, ctx) {
    const id = requireId(input, "Tax rate id is required");
    const em = ctx.container.resolve("em");
    const snapshot = await loadTaxRateSnapshot(em, id);
    if (snapshot) {
      ensureTenantScope(ctx, snapshot.tenantId);
      ensureOrganizationScope(ctx, snapshot.organizationId);
    }
    return snapshot ? { before: snapshot } : {};
  },
  async execute(rawInput, ctx) {
    const { parsed, custom } = parseWithCustomFields(taxRateUpdateSchema, rawInput);
    const em = ctx.container.resolve("em").fork();
    const record = await em.findOne(SalesTaxRate, { id: parsed.id, deletedAt: null });
    if (!record) throw new CrudHttpError(404, { error: "Tax rate not found" });
    const scope = resolveScopeFromUpdate(record, parsed, ctx);
    record.organizationId = scope.organizationId;
    record.tenantId = scope.tenantId;
    if (parsed.channelId !== void 0 && parsed.channelId !== null) {
      const channel = await findOneWithDecryption(em, SalesChannel, { id: parsed.channelId, deletedAt: null }, {}, { tenantId: record.tenantId, organizationId: record.organizationId });
      const channelInScope = assertFound(channel, "Channel not found for tax rate");
      ensureSameScope(channelInScope, record.organizationId, record.tenantId);
    }
    if (parsed.name !== void 0) record.name = parsed.name;
    if (parsed.code !== void 0) record.code = parsed.code;
    if (Object.prototype.hasOwnProperty.call(parsed, "rate")) {
      record.rate = toNumericString(parsed.rate) ?? record.rate;
    }
    if (parsed.countryCode !== void 0) record.countryCode = parsed.countryCode ?? null;
    if (parsed.regionCode !== void 0) record.regionCode = parsed.regionCode ?? null;
    if (parsed.postalCode !== void 0) record.postalCode = parsed.postalCode ?? null;
    if (parsed.city !== void 0) record.city = parsed.city ?? null;
    if (parsed.customerGroupId !== void 0) {
      record.customerGroupId = parsed.customerGroupId ?? null;
    }
    if (parsed.productCategoryId !== void 0) {
      record.productCategoryId = parsed.productCategoryId ?? null;
    }
    if (parsed.channelId !== void 0) record.channelId = parsed.channelId ?? null;
    if (parsed.priority !== void 0) record.priority = parsed.priority ?? 0;
    if (parsed.isCompound !== void 0) record.isCompound = parsed.isCompound;
    if (parsed.isDefault !== void 0) record.isDefault = parsed.isDefault;
    if (parsed.metadata !== void 0) {
      record.metadata = parsed.metadata ? cloneJson(parsed.metadata) : null;
    }
    if (Object.prototype.hasOwnProperty.call(parsed, "startsAt")) {
      record.startsAt = parsed.startsAt ?? null;
    }
    if (Object.prototype.hasOwnProperty.call(parsed, "endsAt")) {
      record.endsAt = parsed.endsAt ?? null;
    }
    await em.flush();
    if (record.isDefault) {
      await deactivateOtherDefaultTaxRates(em, record);
    }
    if (custom && Object.keys(custom).length) {
      await setCustomFieldsIfAny({
        dataEngine: ctx.container.resolve("dataEngine"),
        entityId: E.sales.sales_tax_rate,
        recordId: record.id,
        organizationId: record.organizationId,
        tenantId: record.tenantId,
        values: custom
      });
    }
    return { taxRateId: record.id };
  },
  captureAfter: async (_input, result, ctx) => {
    const em = ctx.container.resolve("em").fork();
    return loadTaxRateSnapshot(em, result.taxRateId);
  },
  buildLog: async ({ snapshots }) => {
    const before = snapshots.before;
    const after = snapshots.after;
    if (!before || !after) return null;
    const { translate } = await resolveTranslations();
    return {
      actionLabel: translate("sales.audit.tax-rates.update", "Update tax rate"),
      resourceKind: "sales.tax-rate",
      resourceId: before.id,
      tenantId: before.tenantId,
      organizationId: before.organizationId,
      snapshotBefore: before,
      snapshotAfter: after,
      changes: buildChanges(
        before,
        after,
        Object.keys({ ...before ?? {}, ...after ?? {} })
      ),
      payload: {
        undo: {
          before,
          after
        }
      }
    };
  },
  undo: async ({ logEntry, ctx }) => {
    const payload = extractUndoPayload(logEntry);
    const before = payload?.before;
    if (!before) return;
    const em = ctx.container.resolve("em").fork();
    let record = await em.findOne(SalesTaxRate, { id: before.id });
    if (!record) {
      record = em.create(SalesTaxRate, taxRateSeedFromSnapshot(before));
      em.persist(record);
    }
    ensureTenantScope(ctx, before.tenantId);
    ensureOrganizationScope(ctx, before.organizationId);
    applyTaxRateSnapshot(record, before);
    await em.flush();
    const resetValues = buildCustomFieldResetMap(before.custom ?? void 0, payload?.after?.custom ?? void 0);
    if (Object.keys(resetValues).length) {
      await setCustomFieldsIfAny({
        dataEngine: ctx.container.resolve("dataEngine"),
        entityId: E.sales.sales_tax_rate,
        recordId: before.id,
        organizationId: before.organizationId,
        tenantId: before.tenantId,
        values: resetValues
      });
    }
  }
};
const deleteTaxRateCommand = {
  id: "sales.tax-rates.delete",
  async prepare(input, ctx) {
    const id = requireId(input, "Tax rate id is required");
    const em = ctx.container.resolve("em");
    const snapshot = await loadTaxRateSnapshot(em, id);
    if (snapshot) {
      ensureTenantScope(ctx, snapshot.tenantId);
      ensureOrganizationScope(ctx, snapshot.organizationId);
    }
    return snapshot ? { before: snapshot } : {};
  },
  async execute(input, ctx) {
    const id = requireId(input, "Tax rate id is required");
    const em = ctx.container.resolve("em").fork();
    const record = await em.findOne(SalesTaxRate, { id });
    if (!record) throw new CrudHttpError(404, { error: "Tax rate not found" });
    ensureTenantScope(ctx, record.tenantId);
    ensureOrganizationScope(ctx, record.organizationId);
    const snapshot = await loadTaxRateSnapshot(ctx.container.resolve("em"), id);
    em.remove(record);
    await em.flush();
    if (snapshot?.custom && Object.keys(snapshot.custom).length) {
      const resetValues = buildCustomFieldResetMap(snapshot.custom, void 0);
      if (Object.keys(resetValues).length) {
        await setCustomFieldsIfAny({
          dataEngine: ctx.container.resolve("dataEngine"),
          entityId: E.sales.sales_tax_rate,
          recordId: id,
          organizationId: record.organizationId,
          tenantId: record.tenantId,
          values: resetValues
        });
      }
    }
    return { taxRateId: id };
  },
  buildLog: async ({ snapshots }) => {
    const before = snapshots.before;
    if (!before) return null;
    const { translate } = await resolveTranslations();
    return {
      actionLabel: translate("sales.audit.tax-rates.delete", "Delete tax rate"),
      resourceKind: "sales.tax-rate",
      resourceId: before.id,
      tenantId: before.tenantId,
      organizationId: before.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 record = await em.findOne(SalesTaxRate, { id: before.id });
    if (!record) {
      record = em.create(SalesTaxRate, taxRateSeedFromSnapshot(before));
      em.persist(record);
    }
    ensureTenantScope(ctx, before.tenantId);
    ensureOrganizationScope(ctx, before.organizationId);
    applyTaxRateSnapshot(record, before);
    await em.flush();
    if (before.custom && Object.keys(before.custom).length) {
      await setCustomFieldsIfAny({
        dataEngine: ctx.container.resolve("dataEngine"),
        entityId: E.sales.sales_tax_rate,
        recordId: before.id,
        organizationId: before.organizationId,
        tenantId: before.tenantId,
        values: before.custom
      });
    }
  }
};
registerCommand(createChannelCommand);
registerCommand(updateChannelCommand);
registerCommand(deleteChannelCommand);
registerCommand(createDeliveryWindowCommand);
registerCommand(updateDeliveryWindowCommand);
registerCommand(deleteDeliveryWindowCommand);
registerCommand(createShippingMethodCommand);
registerCommand(updateShippingMethodCommand);
registerCommand(deleteShippingMethodCommand);
registerCommand(createPaymentMethodCommand);
registerCommand(updatePaymentMethodCommand);
registerCommand(deletePaymentMethodCommand);
registerCommand(createTaxRateCommand);
registerCommand(updateTaxRateCommand);
registerCommand(deleteTaxRateCommand);
//# sourceMappingURL=configuration.js.map
