using Application.Services.Database.MongoDB; using Application.Services.Database.PostgreSQL; using Domain.Entities; namespace Application.Endpoints.Appointments.DeleteAppointment; public class DeleteAppointmentHandler( IAppointmentsMongoDbService appointmentsMongoDbService, IPatientRepository patientRepository, IDoctorRepository doctorRepository) { public async Task Handle(AppointmentInformation request, CancellationToken token) { var validation = new DeleteAppointmentValidator(appointmentsMongoDbService, doctorRepository, patientRepository); var validationResult = await validation.ValidateAsync(request, token); if (!validationResult.IsValid) { var firstError = validationResult.Errors.FirstOrDefault(); var errorCode = int.TryParse(firstError.ErrorCode, out var code) ? code : -1; var errorMessage = firstError.ErrorMessage; return new BaseResponse { StatusCode = errorCode, Message = errorMessage, Data = null }; } var appointmentId = IdentifierGenerator.GenerateId(request.DoctorId, request.PatientId); var criteria = new List<(string FieldName, string Value)> { ("_id", appointmentId) }; var appointments = await appointmentsMongoDbService.FindAsync(criteria, token); if (!appointments.Any()) return new BaseResponse { StatusCode = HttpStatusCodes.NotFound, Message = "Appointment not found in system.", Data = null }; var appointment = appointments[0]; appointment.RemoveAppointment(request.Appointment); await appointmentsMongoDbService.ModifyAsync("_id", appointmentId, appointment, token); return new BaseResponse { StatusCode = HttpStatusCodes.OK, Message = "Appointment successfully removed.", Data = null }; } }