import { getRecipientUserIdsForFeature } from "../../notifications/lib/notificationRecipients.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("inbox_ops").child({ component: "messages" });
function asContainer(resolver) {
  return resolver;
}
const SYSTEM_USER_ID = "00000000-0000-0000-0000-000000000000";
async function resolveMessageSenderUserId(em, forwardedByEmail, recipientUserIds, scope) {
  try {
    const db = em.getKysely();
    const normalizedEmail = forwardedByEmail.trim().toLowerCase();
    if (normalizedEmail) {
      const row = await db.selectFrom("users").select("id").where("email", "=", normalizedEmail).where("deleted_at", "is", null).executeTakeFirst();
      if (row?.id) return row.id;
    }
  } catch {
  }
  if (recipientUserIds.length > 0) return recipientUserIds[0];
  return SYSTEM_USER_ID;
}
function resolveCommandBus(container) {
  try {
    const bus = container.resolve("commandBus");
    return bus && typeof bus.execute === "function" ? bus : null;
  } catch {
    return null;
  }
}
async function createMessageRecordForEmail(email, ctx) {
  try {
    const commandBus = resolveCommandBus(ctx.container);
    if (!commandBus) return null;
    const em = ctx.container.resolve("em");
    const db = em.getKysely();
    const recipientUserIds = await getRecipientUserIdsForFeature(
      db,
      ctx.scope.tenantId,
      "inbox_ops.proposals.view"
    );
    const recipients = recipientUserIds.map((userId) => ({ userId, type: "to" }));
    const bodyText = email.rawText || email.cleanedText || "";
    const senderUserId = await resolveMessageSenderUserId(
      em,
      email.forwardedByAddress,
      recipientUserIds,
      ctx.scope
    );
    const { result } = await commandBus.execute("messages.messages.compose", {
      input: {
        type: "inbox_ops.email",
        visibility: recipients.length > 0 ? "internal" : "public",
        sourceEntityType: "inbox_ops:inbox_email",
        sourceEntityId: email.id,
        externalEmail: email.forwardedByAddress,
        externalName: email.forwardedByName || void 0,
        recipients,
        subject: email.subject,
        body: bodyText.slice(0, 5e4),
        bodyFormat: "text",
        priority: "normal",
        isDraft: false,
        sendViaEmail: false,
        objects: [
          {
            entityModule: "inbox_ops",
            entityType: "inbox_email",
            entityId: email.id,
            actionRequired: false
          }
        ],
        tenantId: ctx.scope.tenantId,
        organizationId: ctx.scope.organizationId,
        userId: senderUserId
      },
      ctx: {
        container: asContainer(ctx.container),
        auth: null,
        organizationScope: null,
        selectedOrganizationId: ctx.scope.organizationId,
        organizationIds: [ctx.scope.organizationId]
      }
    });
    const messageId = result?.id ?? null;
    return messageId;
  } catch (err) {
    logger.error("Failed to create message record for email", { err });
    return null;
  }
}
async function createMessageRecordForReply(reply, inboxEmailId, ctx) {
  try {
    const commandBus = resolveCommandBus(ctx.container);
    if (!commandBus) return null;
    const em = ctx.container.resolve("em");
    const db = em.getKysely();
    const recipientUserIds = await getRecipientUserIdsForFeature(
      db,
      ctx.scope.tenantId,
      "inbox_ops.proposals.view"
    );
    if (recipientUserIds.length === 0) return null;
    const recipients = recipientUserIds.map((userId) => ({ userId, type: "to" }));
    const { result } = await commandBus.execute("messages.messages.compose", {
      input: {
        type: "inbox_ops.reply",
        visibility: "internal",
        sourceEntityType: "inbox_ops:inbox_email",
        sourceEntityId: inboxEmailId,
        externalEmail: reply.to,
        externalName: reply.toName ?? void 0,
        recipients,
        subject: reply.subject,
        body: reply.body,
        bodyFormat: "text",
        priority: "normal",
        isDraft: false,
        sendViaEmail: false,
        objects: [
          {
            entityModule: "inbox_ops",
            entityType: "inbox_email",
            entityId: inboxEmailId,
            actionRequired: false
          }
        ],
        tenantId: ctx.scope.tenantId,
        organizationId: ctx.scope.organizationId,
        userId: ctx.scope.userId
      },
      ctx: {
        container: asContainer(ctx.container),
        auth: null,
        organizationScope: null,
        selectedOrganizationId: ctx.scope.organizationId,
        organizationIds: [ctx.scope.organizationId]
      }
    });
    const messageId = result?.id ?? null;
    if (!messageId) return null;
    return { messageId };
  } catch (err) {
    logger.error("Failed to create reply message record", { err });
    return null;
  }
}
export {
  createMessageRecordForEmail,
  createMessageRecordForReply,
  resolveMessageSenderUserId
};
//# sourceMappingURL=messagesIntegration.js.map
