import { IChatRepository } from '../../../Domain/IRepository/IChatRepository'; import { GetChatsByPageQuery } from './GetChatsByPageQuery'; import { ShortChatDto } from '../../DTOs/ChatDto'; import { ChatMapper } from '../../DTOs/Mappers/ChatMapper'; import { logRequest, logError } from '../../Services/Logger'; export class GetChatsByPageQueryHandler { constructor(private readonly chatRepo: IChatRepository) {} async execute(query: GetChatsByPageQuery): Promise<{ chats: ShortChatDto[], totalCount: number }> { try { // Validate pagination parameters if (query.from < 0 || query.to < query.from) { throw new Error('Invalid pagination parameters'); } const limit = query.to - query.from + 1; if (limit > 100) { throw new Error('Page size too large. Maximum 100 records per request'); } logRequest('Get chats by page query started', undefined, undefined, { from: query.from, to: query.to, includeDeleted: query.includeDeleted || false }); const result = query.includeDeleted ? await this.chatRepo.findByPageIncludingDeleted(query.from, query.to) : await this.chatRepo.findByPage(query.from, query.to); logRequest('Get chats by page query completed', undefined, undefined, { from: query.from, to: query.to, returned: result.chats.length, totalCount: result.totalCount, includeDeleted: query.includeDeleted || false }); return { chats: ChatMapper.toShortDtoList(result.chats), totalCount: result.totalCount }; } catch (error) { logError('GetChatsByPageQueryHandler error', error instanceof Error ? error : new Error(String(error))); // Re-throw validation errors as-is if (error instanceof Error && (error.message.includes('Invalid pagination') || error.message.includes('Page size'))) { throw error; } throw new Error('Failed to retrieve chats page'); } } }