using System.Reflection; using adas_core.Application.Exceptions; using adas_core.Application.Repositories.Interfaces; using adas_core.Application.Services.Interfaces; using adas_core.Application.Subscriptions; using adas_core.Domain.Enums; using adas_core.Domain.Models; using adas_core.Domain.Models.DTO; using adas_core.Domain.Models.Masters; using adas_core.Domain.Models.MongoModels; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using MongoDB.Bson; namespace adas_core.Application.Services; /// /// Provides the concrete implementation of the contract, /// encapsulating the business logic required to process discharge operations. /// /// /// This service acts as the default in-memory or infrastructure-backed implementation /// of the discharge operations defined by . /// public class DischargeService : IDischargeService { private readonly ILocalAuditService _auditService; private readonly IClientMessageService _clientMessageService; private readonly IDischargeRepository _dischargeRepository; private readonly IHttpContextAccessor _httpContextAccessor; private readonly ILogger _logger; private readonly IMasterListServiceFactory _masterListServiceFactory; private readonly Lazy _patientServiceLazy; private readonly IPointOfCareService _pointOfCareService; private readonly ISubscribersService _subscribersService; private readonly IUnitService _unitService; public DischargeService(ILogger logger, ISubscribersService subscribersService, IDischargeRepository dischargeRepository, Lazy patientServiceLazy, IClientMessageService clientMessageService, IPointOfCareService pointOfCareService, IHttpContextAccessor httpContextAccessor, ILocalAuditService auditService, IUnitService unitService, IMasterListServiceFactory masterListServiceFactory) { _logger = logger; _subscribersService = subscribersService; _dischargeRepository = dischargeRepository; _patientServiceLazy = patientServiceLazy; _clientMessageService = clientMessageService; _pointOfCareService = pointOfCareService; _pointOfCareService = pointOfCareService; _httpContextAccessor = httpContextAccessor; _auditService = auditService; _unitService = unitService; _masterListServiceFactory = masterListServiceFactory; } /// /// Deletes a discharge record asynchronously. The method is intended to validate that the patient /// can be discharged (requiring both medical and administrative discharge values and an allowed /// discharge status), and otherwise falls back to deleting the discharge by its identifier. /// /// The discharge entity to be deleted. public async Task DeleteDischargeAsync(Discharge discharge) { //var patient = await _patientServiceLazy.Value.FindById(discharge.PatientId); //if (!discharge.MedicalDischarge.HasValue || !discharge.AdminDischarge.HasValue // // || DischargeStatusType.NoAltable.ToString().Equals(patient?.DischargeStatus?.OptionType) // ) //{ // _logger.LogError("The patient cannot be discharged"); // return; //} await DeleteDischargeByIdAsync(discharge.Id); } /// /// Deletes a discharge record by its identifier. If the discharge is not found, an error is logged and the operation is skipped; otherwise the record is removed, an audit log entry is created, and a delete broadcast is sent. /// /// The unique identifier of the discharge to delete. public async Task DeleteDischargeByIdAsync(ObjectId dischargeId) { try { var dischargeAux = await _dischargeRepository.FindById(dischargeId); if (dischargeAux == null) { _logger.LogError("Error Discharge not found, id: {discharge} ", dischargeId); return; } await _dischargeRepository.Delete(dischargeId); _logger.LogInformation("Discharge id: {dischargeId} DELETED ", dischargeId); //var patient = await _patientServiceLazy.Value.FindById(dischargeAux.PatientId); // if (patient != null) // await _patientServiceLazy.Value.ArchivePatient(patient); // else // _logger.LogError("Patient not found on Discharge id: {discharge} ", dischargeId); await _auditService.CreateAuditLogAsync(_httpContextAccessor.HttpContext?.User!, dischargeAux, null); SendDischargeBroadcast(dischargeAux, OperationType.DeleteDischarge); } catch (Exception ex) { _logger.LogError("Exception deleting discharge id:{admission} . Exception: {ex}", dischargeId, ex); } } /// /// Asynchronously counts the number of discharge records associated with the specified unit identifier. /// /// The identifier of the unit whose discharge records will be counted. /// A task representing the asynchronous operation, containing the total number of discharges for the given unit. public async Task CountDischargesByUnitId(ObjectId unitId) { return await _dischargeRepository.CountByUnitId(unitId); } /// /// Retrieves a discharge by its identifier, enriching the result with patient location details /// when an associated point of care is available. /// /// The unique identifier of the discharge to retrieve. /// The matching , populated with /// information if a point of care is linked; otherwise the discharge as stored. /// Thrown when no discharge is found for the specified /// . public async Task GetDischargeByIdAsync(ObjectId dischargeId) { var result = await _dischargeRepository.FindById(dischargeId) ?? throw new NotFoundException(HttpEnum.ErrorMessage.NotFoundResourceMissing); if (result.PointOfCareId == null) return result; var poc = await _pointOfCareService.GetInfo(result.PointOfCareId.Value, null, false); result.PatientLocation = new PatientLocation(poc?.UnitName, poc?.Bed, poc?.Room); return result; } /// /// Asynchronously retrieves all discharge records from the repository. /// /// A task that represents the asynchronous operation, containing an enumerable collection of records. public async Task> GetDischargesAsync() { return await _dischargeRepository.FindAll(); } /// /// Retrieves the discharge record associated with the specified patient identifier, enriching it with patient location details when a point of care is linked. /// /// The unique identifier of the patient whose discharge record should be retrieved. /// A object populated with patient location information when a point of care is associated, or null if no discharge is found or an error occurs. public async Task GetDischargeByPatientId(ObjectId patientId) { try { var discharge = await _dischargeRepository.GetByPatientId(patientId); if (discharge == null) _logger.LogError("Discharge not found by patient Id {id}", patientId); if (discharge is { PointOfCareId: not null }) { var poc = await _pointOfCareService.GetInfo(discharge.PointOfCareId.Value, null, false); discharge.PatientLocation = new PatientLocation(poc?.UnitName, poc?.Bed, poc?.Room); } return discharge; } catch (Exception ex) { _logger.LogError("Exception getting discharge by patient id: {id} . Exception: {ex}", patientId, ex); return null; } } /// /// Inserts a new discharge record into the repository, verifies its persistence, logs the operation, and broadcasts a notification. /// Throws a if the discharge cannot be retrieved after insertion, indicating a creation failure. /// /// The discharge entity to be inserted. /// The persisted entity retrieved from the repository after insertion. /// Thrown when the inserted discharge cannot be found by its identifier, indicating that the creation failed. public async Task InsertDischarge(Discharge discharge) { await _dischargeRepository.InsertOneAsync(discharge); var dischargeAux = await _dischargeRepository.FindById(discharge.Id) ?? throw new ConflictException(HttpEnum.ErrorMessage.ConflictCreationFailed); _logger.LogInformation("Discharge: {discharge} INSERTED", discharge); await _auditService.CreateAuditLogAsync(_httpContextAccessor.HttpContext?.User!, null, dischargeAux); SendDischargeBroadcast(discharge, OperationType.NewDischarge); return dischargeAux; } /// /// Asynchronously retrieves the associated with the specified patient location. /// Returns null if an exception occurs while accessing the underlying repository. /// /// The patient location used to look up the associated discharge record. /// A if one is found for the given location; otherwise, null when an error occurs. public async Task GetDischargeByLocation(PatientLocation location) { try { return await _dischargeRepository.GetDischargeByLocation(location); } catch (Exception e) { _logger.LogError($"Unable to get discharge by location on service Exception: {e}"); return null; } } /// /// Retrieves a discharge record by the specified point of care identifier and enriches it with patient location details. /// If the discharge is not found, an information message is logged; when a related point of care is available, its unit, bed, and room are mapped to the discharge's . /// On failure, the error is logged and null is returned. /// /// The point of care identifier used to look up the discharge record. /// A with the patient location populated when available, or null if the discharge is not found or an error occurs. public async Task GetDischargeByPointOfCareId(ObjectId poc) { try { var discharge = await _dischargeRepository.GetDischargeByPointOfCareId(poc); if (discharge == null) _logger.LogInformation("Discharge not found by PointOfCareId {id}", poc); if (discharge is { PointOfCareId: not null }) { var pocInfo = await _pointOfCareService.GetInfo(discharge.PointOfCareId.Value, null, false); discharge.PatientLocation = new PatientLocation(pocInfo?.UnitName, pocInfo?.Bed, pocInfo?.Room); } return discharge; } catch (Exception e) { _logger.LogError($"Unable to get discharge by location on service Exception: {e}"); return null; } } /// /// Retrieves a discharge record by its point of care (location) identifier and applies locale-specific data using the associated unit. /// Returns the discharge as-is if no associated unit is found, or null if no discharge exists for the given location. /// /// The ObjectId identifying the point of care (location) whose discharge record should be retrieved. /// The locale used to localize the discharge data when the associated unit is found. /// A containing the localized discharge, the unmodified discharge when its unit cannot be found, or null when no discharge exists for the specified location. public async Task GetDischargeByPointOfCareIdWithLocale(ObjectId location, LocaleEnum dataLocale) { var discharge = await GetDischargeByPointOfCareId(location); if (discharge == null) return null; var unit = await _unitService.FindById(discharge.UnitId); if (unit == null) return discharge; var dischargeWithLocale = await GetDischargeWithLocale(unit, discharge, dataLocale); return dischargeWithLocale; } /// /// Updates an existing discharge record, auditing the change and broadcasting the update. Throws a conflict exception if the discharge cannot be found by its identifier. /// /// The discharge entity to be updated. /// Thrown when no discharge is found with the specified identifier, preventing the update from proceeding. public async Task UpdateDischargeAsync(Discharge discharge) { var oldDischarge = await GetDischargeByIdAsync(discharge.Id) ?? throw new ConflictException(HttpEnum.ErrorMessage.ConflictUpdateFailed); await _dischargeRepository.Update(discharge); await _auditService.CreateAuditLogAsync(_httpContextAccessor.HttpContext?.User!, oldDischarge, discharge); SendDischargeBroadcast(discharge, OperationType.UpdateDischarge); _logger.LogInformation("Discharge: {discharge} UPDATED", discharge); } public async Task SaveRequest(ApiRequest apiRequest) { try { if (apiRequest.Discharge?.Patient == null) return; var patientId = apiRequest.Discharge.Patient.Id; var patient = await _patientServiceLazy.Value.FindById(patientId); if (patient == null) { _logger.LogError("Error discharging patient id: {id} NOT FOUND", patientId); return; } await _patientServiceLazy.Value.Update(apiRequest.Discharge.Patient); switch (apiRequest.Type) { case "NewDischarge": { //TODO: ver qué tipos llegan if (!"Altable".Equals(apiRequest.Discharge.Patient.DischargeStatus?.OptionType)) { _logger.LogError("Error discharging. Patient not altable: {patient}", patient); return; } await _dischargeRepository.InsertOneAsync(apiRequest.Discharge); await _auditService.CreateAuditLogAsync(_httpContextAccessor.HttpContext?.User!, null, apiRequest.Discharge); SendDischargeBroadcast(apiRequest.Discharge, OperationType.NewDischarge); break; } case "UpdateDischarge": { await GetDischargeByIdAsync(apiRequest.Discharge.Id); await UpdateDischargeAsync(apiRequest.Discharge); break; } case "DeleteDischarge": { if (StatusEnum.Discharge.NoAltable.ToString().Equals(patient.DischargeStatus?.OptionType)) { _logger.LogError("Error deleting discharge. Patient altable: {patient}", patient); return; } await DeleteDischargeAsync(apiRequest.Discharge); break; } } } catch (Exception ex) { _logger.LogError("Exception processing discharge api request {discharge} . Exception: {ex}", apiRequest.Discharge, ex); } } /// /// Asynchronously persists the specified API request by executing the save operation on a background thread. /// /// The API request to save. /// A task that completes when the request has been saved. public Task SaveRequestAsync(ApiRequest apiRequest) { return Task.FromResult(Task.Run(async () => { await SaveRequest(apiRequest); })); } // Revisar /// /// Sends a discharge broadcast to all subscribers associated with the discharge's point of care, grouped by their locale. Validates that the point of care identifier is present; logs and returns early if it is null. Exceptions during the broadcast are caught and logged without rethrowing. /// /// The discharge whose point of care is used to locate matching subscribers and whose data is sent in the broadcast. /// The operation type associated with the outgoing message sent to each subscriber. public async void SendDischargeBroadcast(Discharge discharge, OperationType operation) { try { if (discharge.PointOfCareId == null) { _logger.LogError("Error sending discharge broadcast. Unit name is null or empty {discharge} .", discharge); return; } var subscribersGroup = _subscribersService.GetSubscribers() .Where(s => s.LocationIds.Any(c => c == discharge.PointOfCareId)).GroupBy(h => h.Locale) .ToList(); var unit = await _unitService.FindById(discharge.UnitId); foreach (var group in subscribersGroup) { var locale = group.Key ?? LocaleEnum.Default; IEnumerable subscribers = group; foreach (var subscriber in subscribers) { var dischargeWithLocale = await GetDischargeWithLocale(unit, discharge, locale); _ = _clientMessageService.SendAsync(subscriber.Id, operation, dischargeWithLocale); } } } catch (Exception ex) { _logger.LogError("Exception sending discharge broadcast. Operation type: {op}. Exception: {ex}", operation.ToString(), ex); } } /// /// Updates the master list option for the specified units and type, then records an audit log entry and broadcasts the change for each affected discharge. /// /// The master list update options to apply to the discharges. /// The collection of units whose associated discharges will be updated. /// The name of the master list type used to target the update. public async Task UpdatePatientMasterListItemChange(UpdateOptionMasterListDto opt, IEnumerable unitList, string typeName) { var unitIds = unitList.Select(x => x.Id).ToList(); await _dischargeRepository.GetDischargesByUnitIds(unitIds); var dischargeUpdatedList = await _dischargeRepository.UpdateMasterListOption(unitIds, opt, typeName); var updatedList = dischargeUpdatedList as Discharge[] ?? dischargeUpdatedList.ToArray(); foreach (var discharge in updatedList) { var oldDischarge = updatedList.FirstOrDefault(dis => dis.Id == discharge.Id); await _auditService.CreateAuditLogAsync(_httpContextAccessor.HttpContext?.User!, oldDischarge!, discharge); SendDischargeBroadcast(discharge, OperationType.UpdateDischarge); } } /// /// Deletes a patient master list option for the specified units and type, then processes the resulting updated discharge records by creating audit log entries and broadcasting update notifications (only when the updated discharge record is found). /// /// The option list entry to be removed from the patient master list. /// The collection of units whose identifiers are used to scope the deletion. /// The name of the master list type/category to which the option belongs. public async Task DeletePatientMasterListItem(OptionList opt, IEnumerable unitList, string typeName) { var unitIds = unitList.Select(x => x.Id).ToList(); var patientUpdatedList = await _dischargeRepository.DeleteMasterListOption(unitIds, opt, typeName); foreach (var discharge in patientUpdatedList) { var dischargeUpdated = await GetDischargeByIdAsync(discharge.Id); await _auditService.CreateAuditLogAsync(_httpContextAccessor.HttpContext?.User!, discharge, null); if (dischargeUpdated != null) SendDischargeBroadcast(discharge, OperationType.UpdateDischarge); } } /// /// Asynchronously deletes all discharge records associated with the specified unit identifier by delegating the operation to the discharge repository. /// /// The unique identifier of the unit whose discharge records should be removed. public async Task DeleteDischargesByUnitId(ObjectId unitId) { await _dischargeRepository.DeleteByUnitId(unitId); } /// /// Returns the given with its configurable option names translated according to the specified . /// When is null or the locale is , the discharge is returned unchanged. /// Otherwise, the configured service and destination options are looked up in the locale-specific master lists and their Name values are updated; fields without a matching list, missing properties, null values, or without a translation are left untouched. /// /// Source of the master list identifiers used to resolve locale-specific options; when null, no translation is performed. /// Discharge instance whose option names may be translated in place. /// Target locale used to load the appropriate master list; when set to , the discharge is returned without changes. /// The same instance, with translated option names when a matching locale-specific entry is found. private async Task GetDischargeWithLocale(Unit? unit, Discharge discharge, LocaleEnum locale) { if (unit == null) return discharge; if (locale == LocaleEnum.Default) return discharge; // Campos del discharge que deben traducirse var listMap = new List<(string field, ObjectId? listId, MasterListType type)> { ("serviceOption", unit.ServiceListId, MasterListType.ServiceList), ("destinationOption", unit.DestinationListId, MasterListType.DestinationList) }; foreach (var (field, listId, masterListType) in listMap) { if (listId == null) continue; // Obtener propiedad desde DISCHARGE, no Patient var prop = typeof(Discharge).GetProperty( field, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); if (prop == null) continue; var propValue = prop.GetValue(discharge); if (propValue == null) continue; // Cargar master list traducida según locale var listObj = await _masterListServiceFactory .GetMasterListById(masterListType, listId.Value, locale); if (listObj == null) continue; var master = listObj as dynamic; IEnumerable masterOptions = master.Options; // El campo puede ser OptionList simple if (propValue is OptionList { Id: not null } option) { var translated = masterOptions.FirstOrDefault(o => o.Id == option.Id); if (translated != null) option.Name = translated.Name; // Solo traducimos el nombre } } return discharge; } }