using Heimdall.Domain.Enums;
using Heimdall.Domain.Primitives;
namespace Heimdall.Domain.Entities;
///
/// An event detected on a camera stream — motion, person, vehicle, face, etc.
/// Stores AI detection results with confidence, bounding boxes, and snapshots.
///
public class CameraEvent : Entity, IAuditableEntity
{
public Guid CameraId { get; private set; }
public Guid? AgentId { get; private set; }
public EventType Type { get; private set; }
public double Confidence { get; private set; }
public string? Label { get; private set; } // Human-readable label (e.g. "John Doe", "AB-123-CD")
public string? SnapshotUrl { get; private set; } // S3 key or URL to snapshot image
public string? SnapshotThumbUrl { get; private set; } // Thumbnail S3 key or URL
public string? SnapshotObjectKey { get; private set; }
public string? SnapshotThumbObjectKey { get; private set; }
public StorageProvider? SnapshotStorageProvider { get; private set; }
public string? SnapshotStorageRoot { get; private set; }
public string? SnapshotStorageEndpoint { get; private set; }
public string? SnapshotStorageBucket { get; private set; }
public string? MetadataJson { get; private set; } // JSON: bounding boxes, track ID, etc.
public DateTime OccurredAt { get; private set; }
// ── Relations métier (spec 2.1/2.2) ─────────────────────────────
/// Vehicle linked to this event (Event → Vehicle N:1).
public Guid? VehicleId { get; private set; }
/// Known person linked by face recognition; kept as an application-level reference because the table is partitioned.
public Guid? PersonId { get; private set; }
/// Recording segment linked to this event (Event → Recording N:1).
public Guid? RecordingId { get; private set; }
/// Parent event for event hierarchies (Event → Event N:1).
public Guid? ParentEventId { get; private set; }
// ── Déduplication (spec 2.1) ────────────────────────────────────
/// Stable hash of detection content used for deduplication.
public string? DetectionHash { get; private set; }
/// True when the event was suppressed (duplicate / low value).
public bool IsSuppressed { get; private set; }
/// Tracking identifier grouping frames of the same object.
public string? TrackId { get; private set; }
// Audit
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
// Navigation
public Camera Camera { get; private set; } = null!;
// Note: Vehicle, Recording, ParentEvent navigations removed for partitioned table
// compatibility. PostgreSQL requires FK columns to include the partition key (OccurredAt),
// which is not possible with the current schema of those tables.
// FK IDs (VehicleId, RecordingId, ParentEventId) are retained for application-level queries.
private CameraEvent() { } // EF Core
public CameraEvent(Guid cameraId, EventType type, double confidence, DateTime? occurredAt = null, Guid? id = null)
: base(id ?? Guid.NewGuid())
{
CameraId = cameraId;
Type = type;
Confidence = confidence;
OccurredAt = NormalizeOccurredAt(occurredAt ?? DateTime.UtcNow);
}
/// Normalizes event timestamps to UTC and PostgreSQL's microsecond precision.
public static DateTime NormalizeOccurredAt(DateTime value)
{
var utc = value.Kind switch
{
DateTimeKind.Local => value.ToUniversalTime(),
DateTimeKind.Unspecified => DateTime.SpecifyKind(value, DateTimeKind.Utc),
_ => value
};
return new DateTime(utc.Ticks - utc.Ticks % 10, DateTimeKind.Utc);
}
public void SetSnapshot(string snapshotUrl, string? thumbUrl = null)
{
SnapshotUrl = snapshotUrl;
if (thumbUrl is not null)
SnapshotThumbUrl = thumbUrl;
}
public StorageLocation? GetSnapshotLocation()
{
if (SnapshotObjectKey is null || SnapshotStorageProvider is null) return null;
var location = new StorageLocation(SnapshotStorageProvider.Value,
SnapshotStorageRoot, SnapshotStorageEndpoint, SnapshotStorageBucket);
return location.IsComplete ? location : null;
}
public void SetStoredSnapshot(string objectKey, StorageLocation location, string? thumbObjectKey = null)
{
if (string.IsNullOrWhiteSpace(objectKey)) throw new ArgumentException("Snapshot object key is required", nameof(objectKey));
ArgumentNullException.ThrowIfNull(location);
if (!location.IsComplete) throw new ArgumentException("Snapshot storage location is incomplete", nameof(location));
SnapshotObjectKey = objectKey;
SnapshotThumbObjectKey = thumbObjectKey;
SnapshotStorageProvider = location.Provider;
SnapshotStorageRoot = location.LocalRoot;
SnapshotStorageEndpoint = location.S3Endpoint;
SnapshotStorageBucket = location.S3Bucket;
SnapshotUrl = $"/api/events/{Id:D}/snapshot/content";
SnapshotThumbUrl = thumbObjectKey is null ? null : $"/api/events/{Id:D}/snapshot/thumbnail";
}
public void SetMetadata(string? label, string? metadataJson)
{
Label = label;
MetadataJson = metadataJson;
}
public void AssignAgent(Guid agentId) => AgentId = agentId;
public void AssignVehicle(Guid vehicleId) => VehicleId = vehicleId;
public void AssignPerson(Guid personId) => PersonId = personId;
public void AssignRecording(Guid recordingId) => RecordingId = recordingId;
public void AssignParentEvent(Guid parentEventId) => ParentEventId = parentEventId;
public void SetTrackId(string trackId) => TrackId = trackId;
public void SetDetectionHash(string detectionHash) => DetectionHash = detectionHash;
public void SetSuppressed(bool suppressed) => IsSuppressed = suppressed;
}