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 occurredAt = CameraEvent.NormalizeOccurredAt(request.OccurredAt ?? DateTime.UtcNow); var camera = await _context.Cameras.FindAsync([request.CameraId], ct).ConfigureAwait(false); if (camera is null) return ServiceResult.NotFound("Camera not found"); if (request.PersonId.HasValue) { var personExists = await _context.Persons .AnyAsync(p => p.Id == request.PersonId.Value, ct) .ConfigureAwait(false); if (!personExists) return ServiceResult.Failure("Person not found", 400); } var eventId = request.EventId ?? Guid.NewGuid(); if (request.EventId.HasValue) { var existing = await _context.CameraEvents .Include(e => e.Camera) .FirstOrDefaultAsync(e => e.Id == eventId && e.OccurredAt == occurredAt, ct) .ConfigureAwait(false); if (existing is not null) { if (existing.CameraId != request.CameraId || (request.AgentId.HasValue && existing.AgentId != request.AgentId)) return ServiceResult.Failure("Event ID already belongs to another source", 409); var existingResponse = MapResponse(existing); await _publisher.Publish(new EventCreatedNotification(existingResponse), ct).ConfigureAwait(false); return ServiceResult.Success(existingResponse); } } var ev = new CameraEvent(request.CameraId, request.Type, request.Confidence, occurredAt, eventId); if (request.Label is not null || request.MetadataJson is not null) ev.SetMetadata(request.Label, request.MetadataJson); if (request.PersonId.HasValue) ev.AssignPerson(request.PersonId.Value); if (request.AgentId.HasValue) ev.AssignAgent(request.AgentId.Value); _context.CameraEvents.Add(ev); try { await _context.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false); } catch (DbUpdateException) when (request.EventId.HasValue) { var duplicate = await _context.CameraEvents.AsNoTracking().Include(e => e.Camera) .FirstOrDefaultAsync(e => e.Id == eventId && e.OccurredAt == occurredAt, ct) .ConfigureAwait(false); if (duplicate is null) throw; if (duplicate.CameraId != request.CameraId || (request.AgentId.HasValue && duplicate.AgentId != request.AgentId)) return ServiceResult.Failure("Event ID already belongs to another source", 409); var duplicateResponse = MapResponse(duplicate); await _publisher.Publish(new EventCreatedNotification(duplicateResponse), ct).ConfigureAwait(false); return ServiceResult.Success(duplicateResponse); } var response = MapResponse(ev); await _publisher.Publish(new EventCreatedNotification(response), ct).ConfigureAwait(false); return ServiceResult.Success(response); } private static CameraEventResponse MapResponse(CameraEvent e) => new( e.Id, e.CameraId, e.Camera.SiteId, e.AgentId, e.PersonId, e.Type, e.Confidence, e.Label, e.SnapshotUrl, e.SnapshotThumbUrl, e.MetadataJson, e.OccurredAt, e.CreatedAt); }