import { Injectable } from '@nestjs/common' import { plainToClass } from 'class-transformer' import { addDays } from 'date-fns' import { UnauthorizedError } from '../../errors' import { ChallengeWeek, ChallengePatient, ChallengeDayPatient } from '../../models/challenge' import { PatientRepository, ChallengeWeekRepository, ChallengePatientRepository, ChallengeDayPatientRepository, } from '../../repositories' @Injectable() export class ChallengeService { constructor( private readonly patientRepository: PatientRepository, private readonly challengeWeekRepository: ChallengeWeekRepository, private readonly challengePatientRepository: ChallengePatientRepository, private readonly challengeDayPatientRepository: ChallengeDayPatientRepository, ) {} async create(data: { patientId: string }): Promise { const patient = await this.patientRepository.get(data.patientId) if (await this.hasOpenChallenge(patient.id)) throw new UnauthorizedError(patient.email, 'Patient is already in a challenge') const challengePatientId = await this.challengePatientRepository.createChallengePatient( plainToClass(ChallengePatient, { patient_id: patient.id }), ) const challengeWeekDays = await this.challengeWeekRepository.getChallengeWeekDays(patient.country_code) challengeWeekDays.map(async challenge_week => { try { await this.challengeDayPatientRepository.createChallengeDayPatient( challenge_week.challenge_days.map(challenge_days => plainToClass(ChallengeDayPatient, { challenge_patient_id: challengePatientId, challenge_day_id: challenge_days.id, available_at: addDays(new Date(), challenge_days.day), }), ), ) } catch (error) { console.log(error) } }) return await this.challengeWeekRepository.getChallengeWithRelationships(patient.id, patient.country_code) } private async hasOpenChallenge(patientId: string): Promise { const openChallente = await this.challengePatientRepository.getOpenChallenge(patientId) return openChallente ? true : false } }