import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
import { ChannelIngestDeadLetter } from "../data/entities.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("communication_channels").child({ component: "dead-letter" });
const DEAD_LETTER_RAW_BODY_MAX_BYTES_DEFAULT = 32768;
function extractExternalUid(message) {
  const meta = message.channelMetadata;
  if (meta && typeof meta.uid === "string") return meta.uid;
  if (meta && typeof meta.uid === "number") return String(meta.uid);
  return null;
}
function truncateRawBody(message) {
  const envCap = Number.parseInt(process.env.OM_CHANNEL_DEAD_LETTER_RAW_BODY_MAX_BYTES ?? "", 10);
  const cap = Number.isFinite(envCap) && envCap > 0 ? envCap : DEAD_LETTER_RAW_BODY_MAX_BYTES_DEFAULT;
  const body = message.body ?? "";
  if (body.length === 0) return null;
  const buf = Buffer.from(body, "utf-8");
  if (buf.byteLength <= cap) return body;
  return `${buf.subarray(0, cap).toString("utf-8")}\u2026[truncated]`;
}
async function writeIngestDeadLetter(args) {
  const { em, scope, channel, message, err, errorMessage } = args;
  const externalMessageId = message.externalMessageId ?? null;
  try {
    if (externalMessageId) {
      const existing = await findOneWithDecryption(
        em,
        ChannelIngestDeadLetter,
        {
          tenantId: scope.tenantId,
          organizationId: scope.organizationId ?? null,
          channelId: channel.id,
          externalMessageId
        },
        void 0,
        { tenantId: scope.tenantId, organizationId: scope.organizationId ?? null }
      );
      if (existing) return;
    }
    const deadLetter = em.create(ChannelIngestDeadLetter, {
      tenantId: scope.tenantId,
      organizationId: scope.organizationId ?? null,
      channelId: channel.id,
      providerKey: channel.providerKey,
      externalUid: extractExternalUid(message),
      externalMessageId,
      errorClass: err instanceof Error ? err.name : "Error",
      errorMessage,
      rawBody: truncateRawBody(message)
    });
    em.persist(deadLetter);
    await em.flush();
  } catch (ddlErr) {
    logger.error("failed to record dead-letter for channel", { channelId: channel.id, err: ddlErr });
  }
}
export {
  extractExternalUid,
  truncateRawBody,
  writeIngestDeadLetter
};
//# sourceMappingURL=dead-letter.js.map
