import { Injectable } from '@nestjs/common' import { AuthTokenResult, Patient } from '../../../models' import { PatientRepository } from '../../../repositories' import { AccountService, RedisService, SMSTokenOptions, TokenService, TokenValidatorService } from '../../../services' @Injectable() export class Accounts { constructor( private readonly patientRepository: PatientRepository, private readonly tokenService: TokenService, private readonly accountService: AccountService, private readonly tokenValidatorService: TokenValidatorService, private readonly redis: RedisService, ) {} async createPatientAndSendToken(patient: Patient, smsOptions: SMSTokenOptions): Promise { patient = await this.accountService.createPatientAndAuth(patient) await this.clearApiCache(patient.login) return this.tokenService.sendAuthToken(patient, { sms: true, email: true }, smsOptions) } async sendTokenToPatient(login: string, smsOptions?: SMSTokenOptions): Promise { const { patient, isNew } = await this.createOrUpdatePatient(login) if (isNew) await this.clearApiCache(patient.login) const token = await this.tokenService.sendAuthToken(patient, { sms: true, email: true }, smsOptions) return { ...token, exists: !isNew } } async validatePatientToken(login: string, token: string): Promise { return this.tokenValidatorService.validatePatientToken(login, token) } private async createOrUpdatePatient(login: string): Promise<{ isNew: boolean; patient: Patient }> { const patient = await this.patientRepository.findByLogin(login) return { isNew: !patient, patient: !patient ? await this.accountService.createPatientIfStudentOrCollaborator(login) : await this.accountService.checkAndUpdatePatient(patient), } } private async clearApiCache(login: string): Promise { await this.redis.set(login, '') } }