import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
import { CommunicationChannel } from "../data/entities.js";
import { notificationTypes } from "../notifications.js";
import {
  buildNotificationFromType,
  buildFeatureNotificationFromType
} from "../../notifications/lib/notificationBuilder.js";
import { resolveNotificationService } from "../../notifications/lib/notificationService.js";
const metadata = {
  event: "communication_channels.channel.requires_reauth",
  persistent: true,
  id: "communication_channels:channel-requires-reauth-notification"
};
const NOTIFICATION_TYPE = "communication_channels.channel.requires_reauth";
const MANAGE_FEATURE = "communication_channels.manage";
function resolveFromCtx(ctx, name) {
  if (typeof ctx?.resolve === "function") return ctx.resolve(name);
  if (ctx?.container && typeof ctx.container.resolve === "function") {
    return ctx.container.resolve(name);
  }
  throw new Error(
    `channel-requires-reauth-notification: subscriber context has no resolver (looking for '${name}')`
  );
}
async function handler(payload, ctx) {
  if (!payload?.channelId || !payload.tenantId) {
    return;
  }
  const typeDef = notificationTypes.find((type) => type.type === NOTIFICATION_TYPE);
  if (!typeDef) return;
  const scope = {
    tenantId: payload.tenantId,
    organizationId: payload.organizationId ?? null
  };
  const em = resolveFromCtx(ctx, "em").fork();
  const channel = await findOneWithDecryption(
    em,
    CommunicationChannel,
    {
      id: payload.channelId,
      tenantId: payload.tenantId,
      organizationId: payload.organizationId ?? null,
      deletedAt: null
    },
    void 0,
    scope
  );
  if (!channel) return;
  const notificationService = resolveNotificationService(ctx);
  const common = {
    sourceEntityType: "communication_channel",
    sourceEntityId: payload.channelId,
    groupKey: payload.channelId
  };
  if (channel.userId) {
    await notificationService.create(
      buildNotificationFromType(typeDef, { ...common, recipientUserId: channel.userId }),
      scope
    );
    return;
  }
  await notificationService.createForFeature(
    buildFeatureNotificationFromType(typeDef, { ...common, requiredFeature: MANAGE_FEATURE }),
    scope
  );
}
export {
  handler as default,
  metadata
};
//# sourceMappingURL=channel-requires-reauth-notification.js.map
