import { findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
import { CommunicationChannel } from "../data/entities.js";
const metadata = {
  event: "auth.user.deleted",
  persistent: true,
  id: "communication_channels:user-deleted-cascade"
};
async function handler(payload, ctx) {
  if (!payload || typeof payload.userId !== "string" || !payload.userId) {
    return;
  }
  if (typeof payload.tenantId !== "string" || !payload.tenantId) {
    return;
  }
  const em = ctx.resolve("em").fork();
  const channels = await findWithDecryption(
    em,
    CommunicationChannel,
    {
      userId: payload.userId,
      tenantId: payload.tenantId,
      ...payload.organizationId !== void 0 ? { organizationId: payload.organizationId ?? null } : {},
      deletedAt: null
    },
    void 0,
    {
      tenantId: payload.tenantId,
      organizationId: payload.organizationId ?? null
    }
  );
  if (channels.length === 0) return;
  let touched = 0;
  for (const channel of channels) {
    if (channel.status === "disconnected" && channel.isActive === false) continue;
    channel.status = "disconnected";
    channel.isActive = false;
    channel.credentialsRef = null;
    channel.lastError = "user-deleted";
    channel.isPrimary = false;
    channel.lastPolledAt = /* @__PURE__ */ new Date();
    touched += 1;
  }
  if (touched > 0) {
    await em.flush();
  }
}
export {
  handler as default,
  metadata
};
//# sourceMappingURL=user-deleted-cascade.js.map
