import { MatrixClient, MatrixEvent } from 'matrix-js-sdk';
import { getEditedEvent, trimReplyFromBody, trimReplyFromFormattedBody } from '../../../utils/room';

/**
 * Build the content to forward:
 * - undecryptable events are refused (would forward `m.bad.encrypted` junk)
 * - edited messages forward the LATEST edit (`m.new_content`), not the
 *   original pre-edit body
 * - reply fallbacks (`> <@user> …` quote + `<mx-reply>` block) are stripped
 *   along with the `m.relates_to` reply/thread relation, so the forwarded
 *   message stands alone in the target room
 */
export function buildForwardContent(
  mx: MatrixClient,
  mEvent: MatrixEvent,
): Record<string, unknown> | undefined {
  if (mEvent.isDecryptionFailure()) return undefined;

  let content = { ...mEvent.getContent() };

  const eventId = mEvent.getId();
  const room = mx.getRoom(mEvent.getRoomId());
  if (eventId && room) {
    const editedEvent = getEditedEvent(eventId, mEvent, room.getUnfilteredTimelineSet());
    const newContent = editedEvent?.getContent()['m.new_content'];
    if (newContent && typeof newContent === 'object') {
      content = { ...(newContent as Record<string, unknown>) };
    }
  }

  delete content['m.relates_to'];
  // Drop intentional mentions so forwarding a message doesn't re-ping the
  // originally-mentioned users (they're not in the destination room's context).
  delete content['m.mentions'];
  if (typeof content.body === 'string') {
    content.body = trimReplyFromBody(content.body);
  }
  if (typeof content.formatted_body === 'string') {
    content.formatted_body = trimReplyFromFormattedBody(content.formatted_body);
  }
  return content;
}
