// messages.listener.ts
import { Injectable } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
import { MessagesService } from './messages.service';
import { CreateMessageDto } from './dtos/create-message.dto';
import { MessagesEventService } from './messages-event.service';
import { InjectRepository } from '@nestjs/typeorm';
import { Conversation } from '@/entities/conversation.entity';
import { Repository } from 'typeorm';

@Injectable()
export class MessagesListener {
  constructor(
    private service: MessagesService,
    private eventService: MessagesEventService,
    @InjectRepository(Conversation)
    readonly repoConversation: Repository<Conversation>,
  ) {}

  // Tự động được gọi khi emit 'messages.receive-conversation'
  @OnEvent(MessagesEventService.EVENTS.RECEIVE_CONVERSATION)
  async handleReceiveConversation(payload: CreateMessageDto[]) {
    if (!payload || !payload.length) {
      // Send local event
      this.eventService.sendEvent(
        MessagesEventService.LOCAL_EVENTS.RECEIVE_CONVERSATION,
        [],
      );

      return;
    }

    const result = await this.service.bulkCreate(
      payload.filter((item) => item.time),
    );

    // Send local event
    this.eventService.sendEvent(
      MessagesEventService.LOCAL_EVENTS.RECEIVE_CONVERSATION,
      result,
    );
  }

  // Tự động được gọi khi emit 'messages.receive-conversations'
  @OnEvent(MessagesEventService.EVENTS.RECEIVE_CONVERSATIONS)
  async handleReceiveConversations(data: Conversation[]) {
    if (!data || data.length <= 0) {
      this.eventService.sendEvent(
        MessagesEventService.LOCAL_EVENTS.RECEIVE_CONVERSATIONS,
        [],
      );
      return;
    }

    const result = await this.repoConversation.save(data);

    // Send local event
    this.eventService.sendEvent(
      MessagesEventService.LOCAL_EVENTS.RECEIVE_CONVERSATIONS,
      result,
    );
  }
}
