using Heimdall.Application.Services; using Heimdall.Application.Localization; using Heimdall.Infrastructure.Data; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; namespace Heimdall.Infrastructure.Jobs; /// /// Hangfire recurring job that sends a daily digest email to users who have it enabled. /// Scheduled daily at 8:00. /// Uses IDbContextFactory to avoid sharing a DbContext across Hangfire worker threads. /// public class DailyDigestJob { private readonly IDbContextFactory _dbFactory; private readonly IEmailService _emailService; private readonly ICameraAccessService _cameraAccess; private readonly ILogger _logger; public DailyDigestJob( IDbContextFactory dbFactory, IEmailService emailService, ICameraAccessService cameraAccess, ILogger logger) { _dbFactory = dbFactory; _emailService = emailService; _cameraAccess = cameraAccess; _logger = logger; } public async Task ExecuteAsync(CancellationToken ct = default) { _logger.LogInformation("Starting daily digest job"); await using var db = await _dbFactory.CreateDbContextAsync(ct); var configs = await db.UserNotificationConfigs .Where(c => c.DailyDigest && c.EmailEnabled && c.EmailAddress != null) .ToListAsync(ct); var userIds = configs.Select(config => config.UserId).Distinct().ToArray(); var languages = await db.Users.AsNoTracking() .Where(user => userIds.Contains(user.Id)) .ToDictionaryAsync(user => user.Id, user => user.Language, ct); var now = DateTime.UtcNow; var from = now.Date; foreach (var config in configs) { try { var cameraIds = await _cameraAccess .GetUserAccessibleCameraIdsAsync(config.UserId, ct) .ConfigureAwait(false); var eventCount = cameraIds.Count > 0 ? await db.CameraEvents .CountAsync(e => e.OccurredAt >= from && e.OccurredAt < now && cameraIds.Contains(e.CameraId), ct) : 0; var unreadNotifications = await db.Notifications .CountAsync(n => n.UserId == config.UserId && !n.IsRead, ct); var language = languages.GetValueOrDefault(config.UserId, config.Language); var subject = ServerText.Get("Digest.Daily.Subject", language); var body = $"""

{ServerText.Get("Digest.Daily.Title", language)}

{ServerText.Get("Digest.Greeting", language)}

  • {ServerText.Get("Digest.Daily.Events", language)} {eventCount}
  • {ServerText.Get("Digest.UnreadNotifications", language)} {unreadNotifications}

{ServerText.Get("Digest.Signoff", language)}

"""; await _emailService.SendEmailAsync(config.EmailAddress!, subject, body, ct).ConfigureAwait(false); _logger.LogDebug("Daily digest sent to {Email}", config.EmailAddress); } catch (Exception ex) { _logger.LogError(ex, "Failed to send daily digest to {Email}", config.EmailAddress); } } _logger.LogInformation("Daily digest completed: {Count} emails sent", configs.Count); } }