import { Inject } from '@nestjs/common';
import { type IQueryHandler, QueryHandler } from '@nestjs/cqrs';
import type { ConversationEntity } from '../../../domain/entities/conversation.entity';
import {
  CONVERSATION_REPOSITORY,
  type IConversationRepository,
} from '../../../domain/repositories/conversation.repository';
import { GetConversationsQuery } from './get-conversations.query';

@QueryHandler(GetConversationsQuery)
export class GetConversationsHandler implements IQueryHandler<GetConversationsQuery> {
  constructor(
    @Inject(CONVERSATION_REPOSITORY)
    private readonly conversationRepo: IConversationRepository,
  ) {}

  async execute(query: GetConversationsQuery): Promise<{ conversations: ConversationEntity[]; total: number }> {
    const [conversations, total] = await Promise.all([
      this.conversationRepo.findByUserId(query.userId, query.limit, query.offset),
      this.conversationRepo.countByUserId(query.userId),
    ]);
    return { conversations, total };
  }
}
