using AutoMapper; using Heimdall.Application.Common; using Heimdall.Application.DTOs; using Heimdall.Application.Notifications.Mapping; using Heimdall.Application.Services; using Heimdall.Domain.Entities; using Heimdall.Domain.Enums; using Heimdall.Infrastructure.Data; using Heimdall.Infrastructure.Data.Interceptors; using Heimdall.Infrastructure.Services; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using NSubstitute; using Shouldly; namespace Heimdall.Infrastructure.Tests.Services; /// /// Unit tests for . /// Uses SQLite in-memory for real EF Core behavior with mocked external channels. /// public class NotificationServiceTests : IDisposable { private readonly SqliteConnection _connection; private readonly AppDbContext _context; private readonly IMapper _mapper; private readonly INotificationBroadcastService _broadcast; private readonly IEmailService _emailService; private readonly IGotifyService _gotifyService; private readonly INotificationRateLimiter _rateLimiter; private readonly ILogger _logger; private readonly NotificationService _service; public NotificationServiceTests() { _connection = new SqliteConnection("DataSource=:memory:"); _connection.Open(); var opts = new DbContextOptionsBuilder() .UseSqlite(_connection) .Options; _context = new AppDbContext(opts, new AuditInterceptor()); _context.Database.EnsureCreated(); // Real AutoMapper with the actual notification mapping profile var mapperConfig = new MapperConfiguration(cfg => cfg.AddProfile()); _mapper = mapperConfig.CreateMapper(); _broadcast = Substitute.For(); _emailService = Substitute.For(); _gotifyService = Substitute.For(); _rateLimiter = Substitute.For(); _logger = Substitute.For>(); _service = new NotificationService( _context, _mapper, _broadcast, _emailService, _gotifyService, _rateLimiter, _logger); } public void Dispose() { _context.Dispose(); _connection.Close(); _connection?.Dispose(); GC.SuppressFinalize(this); } [Fact] public async Task CreateNotificationAsync_ShouldAddAndBroadcast() { // Arrange var userId = Guid.NewGuid(); _rateLimiter.ShouldSend(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(true); // Act var result = await _service.CreateNotificationAsync( userId, "Test Title", "Test message", NotificationType.Info, EventType.PersonDetected, Guid.NewGuid()); // Assert result.IsSuccess.ShouldBeTrue(); result.Data.ShouldNotBeNull(); result.Data.Title.ShouldBe("Test Title"); result.Data.UserId.ShouldBe(userId); // Verify broadcast was called await _broadcast.Received(1).NotifyNewNotification( Arg.Is(d => d!.Title == "Test Title"), Arg.Any()); // Verify it was persisted var count = await _context.Notifications.CountAsync(); count.ShouldBe(1); } [Fact] public async Task CreateNotificationAsync_RateLimited_ShouldSkipSilently() { // Arrange _rateLimiter.ShouldSend(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(false); // Act var result = await _service.CreateNotificationAsync( Guid.NewGuid(), "Test", "Message", NotificationType.Info, EventType.PersonDetected, Guid.NewGuid()); // Assert result.IsSuccess.ShouldBeTrue(); result.Data.ShouldBeNull(); // Silently skipped // Nothing should be persisted var count = await _context.Notifications.CountAsync(); count.ShouldBe(0); // No broadcast should happen await _broadcast.DidNotReceiveWithAnyArgs().NotifyNewNotification(default!, default); } [Fact] public async Task GetUnreadCountAsync_ShouldReturnCount() { // Arrange var userId = Guid.NewGuid(); // Seed notifications directly in the database _context.Notifications.Add(new Notification(userId, "Unread1", "Msg", NotificationType.Info)); _context.Notifications.Add(new Notification(userId, "Unread2", "Msg", NotificationType.Info)); var readNotification = new Notification(userId, "Read", "Msg", NotificationType.Info); readNotification.MarkAsRead(); _context.Notifications.Add(readNotification); await _context.SaveChangesAsync(); // Act var count = await _service.GetUnreadCountAsync(userId); // Assert count.ShouldBe(2); } [Fact] public async Task GetUnreadCountAsync_OtherUsers_NotCounted() { // Arrange var userId = Guid.NewGuid(); var otherUserId = Guid.NewGuid(); _context.Notifications.Add(new Notification(userId, "Mine", "Msg", NotificationType.Info)); _context.Notifications.Add(new Notification(otherUserId, "Theirs", "Msg", NotificationType.Info)); await _context.SaveChangesAsync(); // Act var count = await _service.GetUnreadCountAsync(userId); // Assert count.ShouldBe(1); } [Fact] public async Task CreateNotificationAsync_WithoutRateLimiter_ShouldWork() { // Arrange var userId = Guid.NewGuid(); // cameraId is null, so rate limiter is skipped entirely // Act var result = await _service.CreateNotificationAsync( userId, "No Cam", "Message", NotificationType.Alert, eventType: null, cameraId: null); // Assert result.IsSuccess.ShouldBeTrue(); result.Data.ShouldNotBeNull(); result.Data.Type.ShouldBe(NotificationType.Alert.ToString()); // Broadcast should still be called await _broadcast.Received(1).NotifyNewNotification( Arg.Any(), Arg.Any()); } [Fact] public async Task MarkAsReadAsync_ExistingNotification_MarksItRead() { // Arrange var userId = Guid.NewGuid(); var notification = new Notification(userId, "Read Test", "Msg", NotificationType.Info); _context.Notifications.Add(notification); await _context.SaveChangesAsync(); notification.IsRead.ShouldBeFalse(); // Act await _service.MarkAsReadAsync(notification.Id, userId); // Assert var updated = await _context.Notifications.FindAsync(notification.Id); updated.ShouldNotBeNull(); updated.IsRead.ShouldBeTrue(); updated.ReadAt.ShouldNotBeNull(); } [Fact] public async Task MarkAsReadAsync_OtherUsersNotification_DoesNothing() { // Arrange var ownerId = Guid.NewGuid(); var otherUserId = Guid.NewGuid(); var notification = new Notification(ownerId, "Not Mine", "Msg", NotificationType.Info); _context.Notifications.Add(notification); await _context.SaveChangesAsync(); // Act await _service.MarkAsReadAsync(notification.Id, otherUserId); // Assert — should NOT mark as read since it belongs to another user var updated = await _context.Notifications.FindAsync(notification.Id); updated.ShouldNotBeNull(); updated.IsRead.ShouldBeFalse(); } [Fact] public async Task MarkAllAsReadAsync_MarksAllUserNotifications() { // Arrange var userId = Guid.NewGuid(); _context.Notifications.Add(new Notification(userId, "A", "Msg", NotificationType.Info)); _context.Notifications.Add(new Notification(userId, "B", "Msg", NotificationType.Warning)); _context.Notifications.Add(new Notification(Guid.NewGuid(), "Other", "Msg", NotificationType.Info)); await _context.SaveChangesAsync(); // Act await _service.MarkAllAsReadAsync(userId); // Assert var userUnread = await _context.Notifications .CountAsync(n => n.UserId == userId && !n.IsRead); userUnread.ShouldBe(0); // Other user's notification should remain unread var otherUnread = await _context.Notifications .CountAsync(n => n.UserId != userId && !n.IsRead); otherUnread.ShouldBe(1); } [Fact] public async Task GetNotificationsAsync_ShouldReturnPagedResults() { // Arrange var userId = Guid.NewGuid(); for (int i = 0; i < 5; i++) { _context.Notifications.Add(new Notification(userId, $"Title {i}", $"Msg {i}", NotificationType.Info)); } await _context.SaveChangesAsync(); // Act var result = await _service.GetNotificationsAsync(userId, null, page: 1, pageSize: 3); // Assert result.Items.Count.ShouldBe(3); result.TotalCount.ShouldBe(5); result.Page.ShouldBe(1); result.TotalPages.ShouldBe(2); result.HasNextPage.ShouldBeTrue(); result.HasPreviousPage.ShouldBeFalse(); } [Fact] public async Task GetNotificationsAsync_FilterByRead_ReturnsFiltered() { // Arrange var userId = Guid.NewGuid(); var n1 = new Notification(userId, "Unread", "Msg", NotificationType.Info); var n2 = new Notification(userId, "Read", "Msg", NotificationType.Info); n2.MarkAsRead(); _context.Notifications.Add(n1); _context.Notifications.Add(n2); await _context.SaveChangesAsync(); // Act var unread = await _service.GetNotificationsAsync(userId, isRead: false, page: 1, pageSize: 20); var read = await _service.GetNotificationsAsync(userId, isRead: true, page: 1, pageSize: 20); // Assert unread.Items.Count.ShouldBe(1); unread.TotalCount.ShouldBe(1); read.Items.Count.ShouldBe(1); read.TotalCount.ShouldBe(1); } }