using Heimdall.Application.Services; using Heimdall.Domain.Enums; using MediatR; namespace Heimdall.Application.Events.Notifications; public class EventCreatedNotificationHandler : INotificationHandler { private readonly IEventBroadcastService _broadcast; private readonly ICameraAccessService _cameraAccess; private readonly INotificationService _notifications; public EventCreatedNotificationHandler( IEventBroadcastService broadcast, ICameraAccessService cameraAccess, INotificationService notifications) { _broadcast = broadcast; _cameraAccess = cameraAccess; _notifications = notifications; } public async Task Handle(EventCreatedNotification notification, CancellationToken ct) { await _broadcast.NotifyEventCreated(notification.Event, ct).ConfigureAwait(false); var cameraEvent = notification.Event; var recipients = await _cameraAccess.GetUserIdsWithCameraAccessAsync(cameraEvent.CameraId, ct) .ConfigureAwait(false); var title = cameraEvent.Type switch { EventType.PersonDetected => "Personne détectée", EventType.VehicleDetected => "Véhicule détecté", EventType.UnknownPerson => "Personne inconnue détectée", EventType.FaceRecognized => "Visage reconnu", EventType.LicensePlateDetected => "Plaque détectée", EventType.CameraOffline => "Caméra hors ligne", EventType.CameraOnline => "Caméra en ligne", _ => "Mouvement détecté" }; var message = string.IsNullOrWhiteSpace(cameraEvent.Label) ? $"{title} sur la caméra {cameraEvent.CameraId}." : $"{title} sur la caméra {cameraEvent.CameraId} : {cameraEvent.Label}."; var type = cameraEvent.Type is EventType.UnknownPerson or EventType.CameraOffline ? NotificationType.Alert : cameraEvent.Type == EventType.CameraOnline ? NotificationType.Info : NotificationType.Warning; foreach (var userId in recipients) { var result = await _notifications.CreateNotificationAsync( userId, title, message, type, cameraEvent.Type, cameraEvent.CameraId, cameraEvent.SiteId, cameraEvent.SnapshotUrl, $"/events?cameraId={cameraEvent.CameraId}&eventId={cameraEvent.Id}", sourceEventId: cameraEvent.Id, ct: ct).ConfigureAwait(false); if (!result.IsSuccess) throw new InvalidOperationException($"Could not persist event notification for user {userId}: {result.Error}"); } } }