import { ForbiddenException, Injectable } from "@nestjs/common"; import { EventsGateway } from "../realtime/events.gateway"; import type { CreateMessageDto } from "./dto/create-message.dto"; import { MessagesRepository } from "./repositories/messages.repository"; @Injectable() export class MessagesService { constructor( private readonly messagesRepository: MessagesRepository, private readonly eventsGateway: EventsGateway, ) {} async sendMessage(senderId: string, dto: CreateMessageDto) { let conversation = await this.messagesRepository.findConversationBetweenUsers( senderId, dto.recipientId, ); if (!conversation) { const newConv = await this.messagesRepository.createConversation(); await this.messagesRepository.addParticipant(newConv.id, senderId); await this.messagesRepository.addParticipant(newConv.id, dto.recipientId); conversation = newConv; } const message = await this.messagesRepository.createMessage({ conversationId: conversation.id, senderId, text: dto.text, }); // Notify recipient via WebSocket this.eventsGateway.sendToUser(dto.recipientId, "new_message", { conversationId: conversation.id, message, }); return message; } async getConversations(userId: string) { return this.messagesRepository.findAllConversations(userId); } async getMessages(userId: string, conversationId: string) { const isParticipant = await this.messagesRepository.isParticipant( conversationId, userId, ); if (!isParticipant) { throw new ForbiddenException("You are not part of this conversation"); } return this.messagesRepository.findMessagesByConversationId(conversationId); } }