import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
import { CommunicationChannel } from "../data/entities.js";
import {
  COMMUNICATION_CHANNELS_DISCONNECT_CHANNEL_COMMAND_ID,
  extractSnapshotFromLog
} from "./disconnect-channel.js";
const interceptors = [
  {
    id: "communication_channels.disconnect-channel-before-undo",
    targetCommand: COMMUNICATION_CHANNELS_DISCONNECT_CHANNEL_COMMAND_ID,
    priority: 50,
    async beforeUndo(undoContext, ctxRuntime) {
      const snapshot = extractSnapshotFromLog(
        undoContext.logEntry
      );
      if (!snapshot) {
        return;
      }
      if (!snapshot.previousIsPrimary) {
        return;
      }
      const em = ctxRuntime.container.resolve("em").fork();
      if (!snapshot.tenantId) return;
      const ownedChannel = await findOneWithDecryption(
        em,
        CommunicationChannel,
        { id: snapshot.channelId, tenantId: snapshot.tenantId },
        void 0,
        { tenantId: snapshot.tenantId, organizationId: null }
      );
      if (!ownedChannel) return;
      const otherPrimary = await findOneWithDecryption(
        em,
        CommunicationChannel,
        {
          tenantId: ownedChannel.tenantId,
          organizationId: ownedChannel.organizationId ?? null,
          userId: ownedChannel.userId,
          isPrimary: true,
          deletedAt: null
        },
        void 0,
        {
          tenantId: ownedChannel.tenantId,
          organizationId: ownedChannel.organizationId ?? null
        }
      );
      if (otherPrimary && otherPrimary.id !== snapshot.channelId) {
        const fallback = "Another channel is now primary for this user. Set it as non-primary before restoring the disconnected channel as primary.";
        let message = fallback;
        try {
          const { translate } = await resolveTranslations();
          message = translate("communication_channels.errors.undoBlockedPrimaryConflict", fallback);
        } catch {
          message = fallback;
        }
        return { ok: false, message };
      }
    }
  }
];
var interceptors_default = interceptors;
export {
  interceptors_default as default,
  interceptors
};
//# sourceMappingURL=interceptors.js.map
