import { Inject } from '@nestjs/common';
import { type IQueryHandler, QueryHandler } from '@nestjs/cqrs';
import { ForbiddenException, NotFoundException } from '@modules/shared';
import type { MessageEntity } from '../../../domain/entities/message.entity';
import {
  CONVERSATION_REPOSITORY,
  type IConversationRepository,
} from '../../../domain/repositories/conversation.repository';
import {
  MESSAGE_REPOSITORY,
  type IMessageRepository,
} from '../../../domain/repositories/message.repository';
import { GetMessagesQuery } from './get-messages.query';

@QueryHandler(GetMessagesQuery)
export class GetMessagesHandler implements IQueryHandler<GetMessagesQuery> {
  constructor(
    @Inject(CONVERSATION_REPOSITORY)
    private readonly conversationRepo: IConversationRepository,
    @Inject(MESSAGE_REPOSITORY)
    private readonly messageRepo: IMessageRepository,
  ) {}

  async execute(query: GetMessagesQuery): Promise<MessageEntity[]> {
    // Verify access
    const conversation = await this.conversationRepo.findById(query.conversationId);
    if (!conversation) {
      throw new NotFoundException('Conversation', query.conversationId);
    }

    const isParticipant = conversation.participants.some((p) => p.userId === query.userId);
    if (!isParticipant) {
      throw new ForbiddenException('Bạn không phải là thành viên của hội thoại này');
    }

    return this.messageRepo.findByConversationId(query.conversationId, query.limit, query.before);
  }
}
