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

export async function handleGetRoomMessageStats(query: GetRoomMessageStatsQuery, dataSource: DataSource) {
  const repo = dataSource.getRepository(MessageEntity);
  const { roomId } = query.payload;
  const currentUserId = await getCurrentUserScope(dataSource);

  if (!currentUserId) {
    return { count: 0,
      lastUpdated: 0 };
  }

  const row = await repo.createQueryBuilder('message')
    .select('COUNT(message.id)', 'count')
    .addSelect('MAX(COALESCE(message.editedAt, message.timestamp, 0))', 'lastUpdated')
    .where('message.roomId = :roomId', { roomId })
    .andWhere('message.ownerUserId = :currentUserId', { currentUserId })
    .getRawOne<{ count?: string | number | null; lastUpdated?: string | number | null }>();

  return {
    count: Number(row?.count ?? 0) || 0,
    lastUpdated: Number(row?.lastUpdated ?? 0) || 0
  };
}
