import { Injectable, NotFoundException, ForbiddenException } from '@nestjs/common'; import { PrismaService } from '../prisma/prisma.service'; import { CreateCharacterDto, UpdateCharacterDto } from './dto/create-character.dto'; import { Character } from '@prisma/client'; @Injectable() export class CharacterService { constructor(private prisma: PrismaService) {} async create(userId: string, createCharacterDto: CreateCharacterDto): Promise { return this.prisma.character.create({ data: { ...createCharacterDto, userId, }, }); } async findAllByUser(userId: string): Promise { return this.prisma.character.findMany({ where: { userId }, orderBy: { createdAt: 'desc' }, }); } async findById(id: string, userId?: string): Promise { const character = await this.prisma.character.findUnique({ where: { id }, include: { knowledgeSources: true, }, }); if (!character) { throw new NotFoundException('Character not found'); } // If userId is provided, check if user owns the character or if it's public if (userId && character.userId !== userId && !character.isPublic) { throw new ForbiddenException('You do not have access to this character'); } return character; } async update( id: string, userId: string, updateCharacterDto: UpdateCharacterDto, ): Promise { const character = await this.findById(id, userId); if (character.userId !== userId) { throw new ForbiddenException('You can only update your own characters'); } return this.prisma.character.update({ where: { id }, data: updateCharacterDto, }); } async delete(id: string, userId: string): Promise { const character = await this.findById(id, userId); if (character.userId !== userId) { throw new ForbiddenException('You can only delete your own characters'); } await this.prisma.character.delete({ where: { id }, }); } }