import { DataSource } from 'typeorm';
import { ReactionEntity } from '../../../entities';
import { SaveReactionCommand } from '../../types';

export async function handleSaveReaction(command: SaveReactionCommand, dataSource: DataSource): Promise<void> {
  const repo = dataSource.getRepository(ReactionEntity);
  const { reaction } = command.payload;
  // Deduplicate: skip if same messageId + userId + emoji already exists
  const existing = await repo.findOne({
    where: { messageId: reaction.messageId, userId: reaction.userId, emoji: reaction.emoji }
  });

  if (existing)
    return;

  const entity = repo.create({
    id: reaction.id,
    messageId: reaction.messageId,
    oderId: reaction.oderId ?? null,
    userId: reaction.userId ?? null,
    emoji: reaction.emoji,
    timestamp: reaction.timestamp
  });

  await repo.save(entity);
}
