import { Injectable } from '@nestjs/common'; import { PrismaService } from '../prisma/prisma.service'; @Injectable() export class RoomPackService { constructor(private prisma: PrismaService) {} /** * Create room pack (called when room is created) */ async create(roomId: string, sourcePackId?: string) { const name = `Room Pack ${Date.now()}`; const description = sourcePackId ? 'Copied from source pack' : 'Custom room questions'; let questions: any = []; let questionCount = 0; // If source pack provided, copy questions if (sourcePackId) { const sourcePack = await this.prisma.questionPack.findUnique({ where: { id: sourcePackId }, select: { questions: true, questionCount: true }, }); if (sourcePack && sourcePack.questions) { questions = sourcePack.questions; questionCount = sourcePack.questionCount; } } return this.prisma.roomPack.create({ data: { roomId, name, description, sourcePackId, questions, questionCount, }, }); } /** * Get room pack by roomId */ async findByRoomId(roomId: string) { return this.prisma.roomPack.findUnique({ where: { roomId }, include: { sourcePack: true }, }); } /** * Update room pack questions */ async updateQuestions(roomId: string, questions: any[]) { const questionCount = Array.isArray(questions) ? questions.length : 0; return this.prisma.roomPack.update({ where: { roomId }, data: { questions, questionCount, updatedAt: new Date(), }, }); } /** * Add questions from another pack (import/copy) */ async importQuestions(roomId: string, sourcePackId: string, questionIndices: number[]) { const roomPack = await this.findByRoomId(roomId); const sourcePack = await this.prisma.questionPack.findUnique({ where: { id: sourcePackId }, select: { questions: true }, }); if (!roomPack) { throw new Error('Room pack not found'); } if (!sourcePack || !sourcePack.questions || !Array.isArray(sourcePack.questions)) { throw new Error('Source pack not found or invalid'); } // Get existing questions const existingQuestions = Array.isArray(roomPack.questions) ? (roomPack.questions as any[]) : []; // Import selected questions (create copies) const sourceQuestions = sourcePack.questions as any[]; const questionsToImport = questionIndices .map(idx => sourceQuestions[idx]) .filter(Boolean) .map(q => ({ ...q })); // Deep copy const updatedQuestions = [...existingQuestions, ...questionsToImport]; return this.updateQuestions(roomId, updatedQuestions); } /** * Soft delete room pack */ async softDelete(roomId: string) { return this.prisma.roomPack.update({ where: { roomId }, data: { deletedAt: new Date() }, }); } /** * Hard delete room pack (for cleanup) */ async hardDelete(roomId: string) { return this.prisma.roomPack.delete({ where: { roomId }, }); } }