import { BadRequestException, Inject, Injectable, Logger, NotFoundException, } from '@nestjs/common'; import { v4 as uuidv4 } from 'uuid'; import { PATIENT_PROVIDER, PatientProvider, } from '../domain/ports/patient-provider.interface'; import { TOUR_PROVIDER, TourProvider, } from '../domain/ports/tour-provider.interface'; import { Ticket, TicketId } from '../domain/ticket.entity'; import { TICKET_REPOSITORY, TicketRepository, } from '../domain/ticket.repository.interface'; export interface CreateTicketCommand { patientId: string; initialTourId?: string; } @Injectable() export class CreateTicketUseCase { private readonly logger = new Logger(CreateTicketUseCase.name); constructor( @Inject(TICKET_REPOSITORY) private readonly ticketRepo: TicketRepository, @Inject(TOUR_PROVIDER) private readonly tourProvider: TourProvider, @Inject(PATIENT_PROVIDER) private readonly patientProvider: PatientProvider, ) {} async execute(command: CreateTicketCommand): Promise { const newTicketId = new TicketId(uuidv4()); const ticket = Ticket.create(newTicketId, command.patientId); if (command.patientId) { const patient = await this.patientProvider.findPatientById( command.patientId, ); if (patient) { ticket.updatePatientData(patient); } } if (command.initialTourId) { const tour = await this.tourProvider.findTourById(command.initialTourId); if (!tour) throw new NotFoundException( `initial tour ${command.initialTourId} not found`, ); if (tour.patientId !== command.patientId) { throw new BadRequestException(`Patient mismatch`); } ticket.assignTour(tour); } await this.ticketRepo.save(ticket); return newTicketId.value; } }