import { DataSource } from 'typeorm';
import { MessageEntity } from '../../../entities';
import { GetMessageByIdQuery } from '../../types';
import { rowToMessage } from '../../mappers';
import { loadMessageReactionsMap } from '../../relations';
import { getCurrentUserScope } from '../../current-user-scope';

export async function handleGetMessageById(query: GetMessageByIdQuery, dataSource: DataSource) {
  const repo = dataSource.getRepository(MessageEntity);
  const currentUserId = await getCurrentUserScope(dataSource);

  if (!currentUserId) {
    return null;
  }

  const row = await repo.findOne({ where: { id: query.payload.messageId, ownerUserId: currentUserId } });

  if (!row) {
    return null;
  }

  const reactionsByMessageId = await loadMessageReactionsMap(dataSource, [row.id]);

  return rowToMessage(row, reactionsByMessageId.get(row.id) ?? []);
}
