import { Injectable, Inject, forwardRef } from '@nestjs/common'; import { PrismaService } from '../prisma/prisma.service'; import { customAlphabet } from 'nanoid'; import { GameGateway } from '../game/game.gateway'; const nanoid = customAlphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', 6); @Injectable() export class RoomsService { constructor( private prisma: PrismaService, @Inject(forwardRef(() => GameGateway)) private gameGateway: GameGateway, ) {} async createRoom(hostId: string, questionPackId?: string, settings?: any) { const code = nanoid(); const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000); // 24 hours // Remove undefined values from settings and ensure questionPackId is handled correctly const cleanSettings = settings ? { ...settings } : {}; if ('questionPackId' in cleanSettings) { delete cleanSettings.questionPackId; } const room = await this.prisma.room.create({ data: { code, hostId, expiresAt, ...cleanSettings, questionPackId: questionPackId || null, }, include: { host: true, questionPack: true, }, }); await this.prisma.participant.create({ data: { userId: hostId, roomId: room.id, name: room.host.name || 'Host', role: 'HOST', }, }); return room; } async getRoomByCode(code: string) { return this.prisma.room.findUnique({ where: { code }, include: { host: true, participants: { include: { user: true }, }, questionPack: true, }, }); } async joinRoom(roomId: string, userId: string, name: string, role: 'PLAYER' | 'SPECTATOR') { const participant = await this.prisma.participant.create({ data: { userId, roomId, name, role, }, }); // Получаем обновленную комнату со всеми участниками const room = await this.prisma.room.findUnique({ where: { id: roomId }, include: { host: true, participants: { include: { user: true }, }, questionPack: true, }, }); // Отправляем событие roomUpdate всем клиентам в комнате if (room && this.gameGateway?.server) { this.gameGateway.server.to(room.code).emit('roomUpdate', room); } return participant; } async updateRoomStatus(roomId: string, status: 'WAITING' | 'PLAYING' | 'FINISHED') { return this.prisma.room.update({ where: { id: roomId }, data: { status }, }); } async updateParticipantScore(participantId: string, score: number) { return this.prisma.participant.update({ where: { id: participantId }, data: { score }, }); } async updateQuestionPack(roomId: string, questionPackId: string) { return this.prisma.room.update({ where: { id: roomId }, data: { questionPackId, currentQuestionIndex: 0, revealedAnswers: {}, }, include: { host: true, participants: { include: { user: true }, }, questionPack: true, }, }); } }