import { Injectable, NotFoundException, ForbiddenException } from '@nestjs/common'; import { PrismaService } from '../common/prisma/prisma.service'; @Injectable() export class GroupsService { constructor(private prisma: PrismaService) {} async createGroup(courseId: string, userId: string, name: string, description?: string): Promise { const course = await this.prisma.course.findFirst({ where: { id: courseId, authorId: userId } }); if (!course) throw new ForbiddenException('Only course author can create groups'); return this.prisma.courseGroup.create({ data: { courseId, name, description }, }); } async addMember(groupId: string, userId: string, role = 'student'): Promise { return this.prisma.groupMember.create({ data: { groupId, userId, role }, }); } async getGroupMessages(groupId: string, userId: string): Promise { const member = await this.prisma.groupMember.findUnique({ where: { groupId_userId: { groupId, userId } }, }); if (!member) throw new ForbiddenException('Not a member of this group'); return this.prisma.groupMessage.findMany({ where: { groupId }, include: { user: { select: { id: true, name: true, avatarUrl: true } } }, orderBy: { createdAt: 'asc' }, take: 100, }); } async sendMessage(groupId: string, userId: string, content: string): Promise { const member = await this.prisma.groupMember.findUnique({ where: { groupId_userId: { groupId, userId } }, }); if (!member) throw new ForbiddenException('Not a member of this group'); return this.prisma.groupMessage.create({ data: { groupId, userId, content }, include: { user: { select: { id: true, name: true, avatarUrl: true } } }, }); } }