#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Mapping.Scheduling;
using Lumina.Application.Core.Scheduling.Notifications;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.Scheduling.Events;
///
/// Handler for the domain event raised when a scheduled job is added.
///
public class ScheduledJobAddedDomainEventHandler : IDomainEventHandler
{
private readonly IUnitOfWork _unitOfWork;
private readonly IScheduledJobNotifier _scheduledJobNotifier;
///
/// Initializes a new instance of the class.
///
/// Injected service for notifying the scheduled job changes to SignalR clients.
/// Injected unit of work for interacting with the data access layer repositories.
public ScheduledJobAddedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_scheduledJobNotifier = scheduledJobNotifier;
}
///
/// Handles the event raised when a scheduled job is added.
///
/// The domain event to be handled.
/// Cancellation token that can be used to stop the execution.
public async ValueTask HandleAsync(ScheduledJobAddedDomainEvent domainEvent, CancellationToken cancellationToken)
{
Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
if (getScheduledJobsResult.IsFailure)
throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors);
IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Data.Select(scheduledJob => scheduledJob.ToResponse())];
await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false);
}
}