using Heimdall.Application.Common; using Heimdall.Application.DTOs; using Heimdall.Application.Events.Notifications; using Heimdall.Domain.Entities; using MediatR; using Microsoft.EntityFrameworkCore; namespace Heimdall.Application.Events.Commands.CreateEvent; #pragma warning disable CA1711 // Identifiers should not contain type names like 'Event' in 'EventHandler' — matches MediatR naming convention public class CreateEventHandler : IRequestHandler> #pragma warning restore CA1711 { private readonly IApplicationDbContext _context; private readonly IPublisher _publisher; public CreateEventHandler(IApplicationDbContext context, IPublisher publisher) { _context = context; _publisher = publisher; } public async Task> Handle(CreateEventCommand request, CancellationToken ct) { var camera = await _context.Cameras.FindAsync([request.CameraId], ct); if (camera is null) return ServiceResult.NotFound("Camera not found"); var ev = new CameraEvent(request.CameraId, request.Type, request.Confidence, request.OccurredAt); if (request.Label is not null || request.MetadataJson is not null) ev.SetMetadata(request.Label, request.MetadataJson); _context.CameraEvents.Add(ev); await _context.SaveChangesWithRetryAsync(ct: ct); var response = MapResponse(ev); await _publisher.Publish(new EventCreatedNotification(response), ct); return ServiceResult.Success(response); } private static CameraEventResponse MapResponse(CameraEvent e) => new( e.Id, e.CameraId, e.Camera.SiteId, e.AgentId, e.Type, e.Confidence, e.Label, e.SnapshotUrl, e.SnapshotThumbUrl, e.MetadataJson, e.OccurredAt, e.CreatedAt); }