using Heimdall.Application.Services; using Heimdall.Domain.Entities; using Heimdall.Domain.Enums; using Heimdall.Infrastructure.Data; using Heimdall.Infrastructure.Data.Interceptors; using Heimdall.Infrastructure.Jobs; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging.Abstractions; using NSubstitute; using Shouldly; namespace Heimdall.Infrastructure.Tests; public sealed class DigestJobTests : IDisposable { private readonly SqliteConnection _connection = new("DataSource=:memory:"); private readonly TestDbContextFactory _dbFactory; public DigestJobTests() { _connection.Open(); var options = new DbContextOptionsBuilder() .UseSqlite(_connection) .Options; using var db = new AppDbContext(options, new AuditInterceptor()); db.Database.EnsureCreated(); _dbFactory = new TestDbContextFactory(options); } public void Dispose() { _connection.Dispose(); GC.SuppressFinalize(this); } [Fact] public async Task DailyDigest_UsesUtcDayAndOnlyAccessibleCameraEvents() { var (userId, allowedCameraId, otherCameraId, email) = await SeedUserAndCamerasAsync(daily: true, weekly: false); var now = DateTime.UtcNow; var todayStart = now.Date; await AddEventAsync(allowedCameraId, todayStart.AddMinutes(1)); await AddEventAsync(allowedCameraId, todayStart.AddTicks(-1)); await AddEventAsync(allowedCameraId, now.AddHours(1)); await AddEventAsync(otherCameraId, todayStart.AddMinutes(2)); var access = Substitute.For(); access.GetUserAccessibleCameraIdsAsync(userId, Arg.Any()) .Returns(Task.FromResult(new List { allowedCameraId })); var emailService = Substitute.For(); var job = new DailyDigestJob(_dbFactory, emailService, access, NullLogger.Instance); await job.ExecuteAsync(); await emailService.Received(1).SendEmailAsync( email, Arg.Any(), Arg.Any(), Arg.Any()); var emailArguments = emailService.ReceivedCalls().Single().GetArguments(); ((string)emailArguments[1]!).ShouldContain("quotidien"); ((string)emailArguments[2]!).ShouldContain("aujourd'hui (UTC)"); ((string)emailArguments[2]!).ShouldContain("1"); await access.Received(1).GetUserAccessibleCameraIdsAsync(userId, Arg.Any()); } [Fact] public async Task WeeklyDigest_UsesRollingSevenDayWindowAndOnlyAccessibleCameraEvents() { var (userId, allowedCameraId, otherCameraId, email) = await SeedUserAndCamerasAsync(daily: false, weekly: true); var now = DateTime.UtcNow; await AddEventAsync(allowedCameraId, now.AddDays(-1)); await AddEventAsync(allowedCameraId, now.AddDays(-8)); await AddEventAsync(allowedCameraId, now.AddHours(1)); await AddEventAsync(otherCameraId, now.AddDays(-1)); var access = Substitute.For(); access.GetUserAccessibleCameraIdsAsync(userId, Arg.Any()) .Returns(Task.FromResult(new List { allowedCameraId })); var emailService = Substitute.For(); var job = new WeeklyDigestJob(_dbFactory, emailService, access, NullLogger.Instance); await job.ExecuteAsync(); await emailService.Received(1).SendEmailAsync( email, Arg.Any(), Arg.Any(), Arg.Any()); var emailArguments = emailService.ReceivedCalls().Single().GetArguments(); ((string)emailArguments[1]!).ShouldContain("hebdomadaire"); ((string)emailArguments[2]!).ShouldContain("7 derniers jours (UTC)"); ((string)emailArguments[2]!).ShouldContain("1"); await access.Received(1).GetUserAccessibleCameraIdsAsync(userId, Arg.Any()); } private async Task<(Guid UserId, Guid AllowedCameraId, Guid OtherCameraId, string Email)> SeedUserAndCamerasAsync( bool daily, bool weekly) { var userId = Guid.NewGuid(); const string email = "digest@example.test"; await using var db = await _dbFactory.CreateDbContextAsync(); var site = new Site("Digest site"); db.Sites.Add(site); await db.SaveChangesAsync(); var allowedCamera = new Camera(site.Id, "Allowed camera"); var otherCamera = new Camera(site.Id, "Other camera"); db.Cameras.AddRange(allowedCamera, otherCamera); var config = new UserNotificationConfig(userId); config.UpdateEmail(email, enabled: true); config.UpdateDigests(daily, weekly); db.UserNotificationConfigs.Add(config); await db.SaveChangesAsync(); return (userId, allowedCamera.Id, otherCamera.Id, email); } private async Task AddEventAsync(Guid cameraId, DateTime occurredAt) { await using var db = await _dbFactory.CreateDbContextAsync(); db.CameraEvents.Add(new CameraEvent(cameraId, EventType.MotionDetected, 0.9, occurredAt)); await db.SaveChangesAsync(); } private sealed class TestDbContextFactory(DbContextOptions options) : IDbContextFactory { private static readonly AuditInterceptor Audit = new(); public AppDbContext CreateDbContext() => new(options, Audit); public Task CreateDbContextAsync(CancellationToken cancellationToken = default) => Task.FromResult(new AppDbContext(options, Audit)); } }