import { DELETED_MESSAGE_CONTENT, type Message } from '../../../../shared-kernel';
import { getMessageRevision } from './message-integrity.rules';

/** Extracts the effective timestamp from a message (editedAt takes priority). */
export function getMessageTimestamp(msg: Message): number {
  return msg.editedAt || msg.timestamp || 0;
}

/** Whether the UI should show the "(edited)" label for a message. */
export function shouldShowMessageEditedLabel(
  message: Pick<Message, 'editedAt' | 'timestamp' | 'revision' | 'isDeleted'>
): boolean {
  if (message.isDeleted || message.editedAt === undefined) {
    return false;
  }

  if (getMessageRevision(message) > 0) {
    return true;
  }

  return typeof message.timestamp === 'number' && message.editedAt > message.timestamp;
}

/** Computes the most recent timestamp across a batch of messages. */
export function getLatestTimestamp(messages: Message[]): number {
  return messages.reduce((max, msg) => Math.max(max, getMessageTimestamp(msg)), 0);
}

/** Strips sensitive content from a deleted message. */
export function normaliseDeletedMessage(message: Message): Message {
  if (!message.isDeleted)
    return message;

  return {
    ...message,
    content: DELETED_MESSAGE_CONTENT,
    reactions: []
  };
}

/** Whether the given user is allowed to edit this message. */
export function canEditMessage(message: Message, userId: string): boolean {
  return message.senderId === userId;
}
