import { BadRequestException, Injectable, UnprocessableEntityException } from '@nestjs/common' import { CreateChallengeActionDto } from './dto/create-challenge-action.dto' import { UpdateChallengeActionDto } from './dto/update-challenge-action.dto' import { ChallengeAction, 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 { FilterChallengeActionsDto } from './dto/filter-challenge-action.dto' @Injectable() export class ChallengeActionsService { constructor(private prisma: PrismaService) { } async create(authenticatedPlayer: Player, createChallengeActionDto: CreateChallengeActionDto): Promise { const data = { ...createChallengeActionDto, playerId: authenticatedPlayer.id } return await this.prisma.challengeAction.create({ data: data, }) } async findAll(queryPagination: QueryPaginationDto, filterChallengeActions: FilterChallengeActionsDto): Promise<[ChallengeAction[], number]> { return [ await this.prisma.challengeAction.findMany({ ...paginate(queryPagination), where: filterChallengeActions, }), await this.prisma.challengeAction.count(), ] } async findOne(id: number): Promise { return await this.prisma.challengeAction.findUnique({ where: { id }, }) } async update(id: number, updateChallengeActionDto: UpdateChallengeActionDto): Promise { return await this.prisma.challengeAction.update({ where: { id }, data: updateChallengeActionDto, }) } async remove(id: number): Promise { return await this.prisma.challengeAction.delete({ where: { id }, }) } async endCurrentChallenge(player: Player, success: boolean): Promise { const challengeAction = await this.prisma.challengeAction.findFirst({ where: { playerId: player.id, active: true, } }) if (!challengeAction) throw new BadRequestException("Aucun défi n'est en cours") let data const now = new Date() if (success) { data = { success: success, active: false, end: now, } } else { data = { success: success, active: false, end: now, penaltyStart: now, penaltyEnd: new Date(now.getTime() + 45 * 60 * 1000), } } return await this.prisma.challengeAction.update({ where: { id: challengeAction.id, }, data: data, }) } }