Files
Heimdall/src/Heimdall.Application/Events/Commands/CreateEvent/CreateEventHandler.cs
T

69 lines
3.0 KiB
C#
Raw Normal View History

using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
2026-07-22 20:22:34 +00:00
using Heimdall.Application.Events.Notifications;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Events.Commands.CreateEvent;
2026-07-22 20:22:34 +00:00
#pragma warning disable CA1711 // Identifiers should not contain type names like 'Event' in 'EventHandler' — matches MediatR naming convention
public class CreateEventHandler : IRequestHandler<CreateEventCommand, ServiceResult<CameraEventResponse>>
#pragma warning restore CA1711
{
private readonly IApplicationDbContext _context;
2026-07-22 20:22:34 +00:00
private readonly IPublisher _publisher;
2026-07-22 20:22:34 +00:00
public CreateEventHandler(IApplicationDbContext context, IPublisher publisher)
{
_context = context;
_publisher = publisher;
}
public async Task<ServiceResult<CameraEventResponse>> 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<CameraEventResponse>.NotFound("Camera not found");
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)
return ServiceResult<CameraEventResponse>.Success(MapResponse(existing));
}
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);
_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;
return ServiceResult<CameraEventResponse>.Success(MapResponse(duplicate));
}
2026-07-22 20:22:34 +00:00
var response = MapResponse(ev);
await _publisher.Publish(new EventCreatedNotification(response), ct).ConfigureAwait(false);
2026-07-22 20:22:34 +00:00
return ServiceResult<CameraEventResponse>.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);
}