import { DataSource } from 'typeorm';
import { MessageEntity } from '../../../entities';
import { replaceMessageReactions } from '../../relations';
import { SaveMessageCommand } from '../../types';
import { getCurrentUserScope } from '../../current-user-scope';

export async function handleSaveMessage(command: SaveMessageCommand, dataSource: DataSource): Promise<void> {
  const { message } = command.payload;

  await dataSource.transaction(async (manager) => {
    const currentUserId = await getCurrentUserScope(manager);
    const repo = manager.getRepository(MessageEntity);
    const entity = repo.create({
      id: message.id,
      roomId: message.roomId,
      ownerUserId: currentUserId,
      channelId: message.channelId ?? null,
      senderId: message.senderId,
      senderName: message.senderName,
      content: message.content,
      timestamp: message.timestamp,
      editedAt: message.editedAt ?? null,
      revision: message.revision ?? 0,
      headHash: message.headHash ?? null,
      isDeleted: message.isDeleted ? 1 : 0,
      replyToId: message.replyToId ?? null,
      linkMetadata: message.linkMetadata ? JSON.stringify(message.linkMetadata) : null
    });

    await repo.save(entity);
    await replaceMessageReactions(manager, message.id, message.reactions ?? []);
  });
}
