import { ConflictException, Injectable, NotFoundException } from '@nestjs/common' import { CreateChallengeDto } from './dto/create-challenge.dto' import { UpdateChallengeDto } from './dto/update-challenge.dto' import { Challenge, Player } from '@prisma/client' import { PrismaService } from 'src/prisma/prisma.service' import { QueryPaginationDto } from 'src/common/dto/pagination-query.dto' import { paginate } from 'src/common/utils/pagination.utils' import { ChallengeEntity } from './entities/challenge.entity' @Injectable() export class ChallengesService { constructor(private prisma: PrismaService) { } async create(createChallengeDto: CreateChallengeDto): Promise { const data = { ...createChallengeDto } return await this.prisma.challenge.create({ data: data }) } async findAll(queryPagination?: QueryPaginationDto): Promise<[Challenge[], number]> { return [ await this.prisma.challenge.findMany({ ...paginate(queryPagination), include: { action: true, } }), await this.prisma.challenge.count(), ] } async findOne(id: number): Promise { return await this.prisma.challenge.findUnique({ where: { id }, include: { action: true, } }) } async update(id: number, updateChallengeDto: UpdateChallengeDto): Promise { if (!this.findOne(id)) throw new NotFoundException(`Aucun défi n'existe avec l'identifiant ${id}`) return await this.prisma.challenge.update({ where: { id }, data: updateChallengeDto, include: { action: true, } }) } async remove(id: number): Promise { if (!this.findOne(id)) throw new NotFoundException(`Aucun défi n'existe avec l'identifiant ${id}`) return await this.prisma.challenge.delete({ where: { id }, include: { action: true, } }) } async drawRandom(player: Player): Promise { const currentChallengeAction = await this.prisma.challengeAction.findFirst({ where: { playerId: player.id, active: true, } }) if (currentChallengeAction) throw new ConflictException("Un défi est déjà en cours d'accomplissement") const remaningChallenges = await this.prisma.challenge.count({ where: { action: null, } }) const challenge = await this.prisma.challenge.findFirst({ where: { action: null, }, take: 1, skip: Math.random() * remaningChallenges, }) if (!challenge) throw new NotFoundException("Plus aucun défi disponible") const challengeEntity: ChallengeEntity = new ChallengeEntity(challenge) const action = await this.prisma.challengeAction.create({ data: { playerId: player.id, challengeId: challenge.id, active: true, success: false, } }) challengeEntity.action = action return challengeEntity } }