import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
import { createQueue } from "@open-mercato/queue";
import { buildBatchNotificationFromType } from "../../notifications/lib/notificationBuilder.js";
import { resolveNotificationService } from "../../notifications/lib/notificationService.js";
import {
  MESSAGES_EMAIL_QUEUE_NAME
} from "../workers/send-email.worker.js";
import { User } from "../../auth/data/entities.js";
import { Message } from "../data/entities.js";
import { notificationTypes } from "../notifications.js";
const metadata = {
  event: "messages.message.sent",
  persistent: true,
  id: "messages:queue-email-delivery"
};
async function resolveNotificationVariables(payload, ctx) {
  try {
    const em = ctx.resolve("em")?.fork();
    if (!em) return { title: "", from: "" };
    const scope = {
      tenantId: payload.tenantId,
      organizationId: payload.organizationId ?? null
    };
    const whereUser = {
      id: payload.senderUserId,
      tenantId: payload.tenantId,
      deletedAt: null
    };
    if (payload.organizationId !== void 0) {
      whereUser.organizationId = payload.organizationId;
    }
    const [message, sender] = await Promise.all([
      findOneWithDecryption(
        em,
        Message,
        {
          id: payload.messageId,
          tenantId: payload.tenantId,
          deletedAt: null
        },
        void 0,
        scope
      ),
      findOneWithDecryption(
        em,
        User,
        whereUser,
        void 0,
        scope
      )
    ]);
    return {
      title: typeof message?.subject === "string" ? message.subject : "",
      from: typeof sender?.name === "string" && sender.name.trim().length > 0 ? sender.name : typeof sender?.email === "string" ? sender.email : ""
    };
  } catch {
    return { title: "", from: "" };
  }
}
async function handle(payload, ctx) {
  const uniqueRecipientUserIds = Array.from(new Set(payload.recipientUserIds));
  const typeDef = notificationTypes.find((type) => type.type === "messages.new");
  if (typeDef && uniqueRecipientUserIds.length > 0) {
    const variables = await resolveNotificationVariables(payload, ctx);
    const notificationService = resolveNotificationService(ctx);
    const notificationInput = buildBatchNotificationFromType(typeDef, {
      recipientUserIds: uniqueRecipientUserIds,
      titleVariables: variables,
      bodyVariables: variables,
      sourceEntityType: "message",
      sourceEntityId: payload.messageId,
      linkHref: `/backend/messages/${payload.messageId}`
    });
    await notificationService.createBatch(notificationInput, {
      tenantId: payload.tenantId,
      organizationId: payload.organizationId ?? null
    });
  }
  if (!payload.sendViaEmail) {
    return;
  }
  const strategy = process.env.QUEUE_STRATEGY === "async" ? "async" : "local";
  const emailQueue = createQueue(MESSAGES_EMAIL_QUEUE_NAME, strategy);
  for (const recipientUserId of uniqueRecipientUserIds) {
    await emailQueue.enqueue({
      type: "recipient",
      messageId: payload.messageId,
      recipientUserId,
      tenantId: payload.tenantId,
      organizationId: payload.organizationId ?? null
    });
  }
  const externalEmail = payload.externalEmail?.trim();
  if (externalEmail) {
    await emailQueue.enqueue({
      type: "external",
      messageId: payload.messageId,
      email: externalEmail,
      tenantId: payload.tenantId,
      organizationId: payload.organizationId ?? null
    });
  }
}
export {
  handle as default,
  metadata
};
//# sourceMappingURL=message-notification.js.map
