import dayjs from 'dayjs';

/**
 * Convierte el raw de open-wa a un objeto compacto.
 * Solo coloca `media` cuando hay TODO para desencriptar: mediaKey + clientUrl.
 */
export function processMessage(raw) {
  const m = raw?.data ?? raw;               // alias corto

  const base = {
    msgId     : m.id,
    chatId    : m.chatId,
    chatName  : m.chat?.name ?? m.chat?.formattedTitle ?? null,
    senderId  : m.sender?.id ?? m.author ?? null,
    senderName: m.sender?.name ?? m.notifyName ?? null,
    type      : m.type,
    text      : m.text ?? m.caption ?? '',
    fromMe    : !!m.fromMe,
    timestamp : m.timestamp ?? m.t,
    date      : m.timestamp
                ? dayjs.unix(m.timestamp).utcOffset(-360).format('YYYY-MM-DD HH:mm:ss')
                : null,
    hasReactions: (m.reactions?.length ?? 0) > 0 || !!m.hasReaction,
    reactions   : (m.reactions ?? []).map(r => r.aggregateEmoji)
  };

  /* ---------- quoted ---------- */
  if (m.quotedMsg) {
    base.replyTo = {
      id  : m.quotedMsg.id,
      text: m.quotedMsg.text ?? m.quotedMsg.body ?? '',
      from: m.quotedParticipant ?? null,
      type: m.quotedMsg.type
    };
  }

  /* ---------- preview de enlaces ---------- */
  if (m.matchedText) {
    base.preview = {
      url  : m.matchedText,
      title: m.title ?? null,
      description: m.description ?? null
    };
  }

  /* ---------- media listo para desencriptar ---------- */
  const isMediaType = ['image','video','sticker','ptt','audio','document'].includes(m.type);
  const hasKeys     = m.mediaKey || m.mediaData?.mediaKey;
  const hasUrl      = m.clientUrl || m.directPath;

  if (isMediaType && hasKeys && hasUrl) {
    base.media = {
      type     : m.type,
      clientUrl: m.clientUrl ?? m.directPath,
      mimetype : m.mimetype,
      size     : m.size ?? m.mediaData?.size,
      width    : m.width,
      height   : m.height,
      duration : Number(m.duration) || 0,
      filename : m.filename ?? null,
      caption  : m.caption ?? null,

      /* claves para decryptMediaContent */
      mediaKey : m.mediaKey ?? m.mediaData?.mediaKey,
      filehash : m.filehash ?? m.mediaData?.filehash,
      t        : m.t ?? m.timestamp
    };

    if (m.type === 'sticker') {
      Object.assign(base.media, {
        packId  : m.stickerPackId        ?? m.mediaData?.stickerPackId,
        pack    : m.stickerPackName      ?? m.mediaData?.stickerPackName,
        author  : m.stickerPackPublisher ?? m.mediaData?.stickerPackPublisher,
        animated: m.isLottie || m.mediaData?.isAnimated || false
      });
    }
  }

  return base;
}
