using Microsoft.AspNetCore.SignalR; using Microsoft.EntityFrameworkCore; using vendorApproverBackend.Hubs; using vendorApproverBackend.Entities; using vendorApproverBackend.Interfaces; using vendorApproverBackend.Data; namespace vendorApproverBackend.Services { public class NotificationSender : INotificationService { private readonly IHubContext _hubContext; private readonly DataContext _context; public NotificationSender(IHubContext hubContext, DataContext context) { _hubContext = hubContext; _context = context; } public async Task SendNotificationToUser(long userId, NotificationModel notification) { // Save to database first _context.NotificationModels.Add(notification); await _context.SaveChangesAsync(); // Send via SignalR await _hubContext.Clients .Group($"user_{userId}") .SendAsync("ReceiveNotification", notification.ToMap()); } public async Task SendNotificationToUsers(IEnumerable userIds, NotificationModel notification) { // Save to database first _context.NotificationModels.Add(notification); await _context.SaveChangesAsync(); // Send to multiple users var tasks = userIds.Select(userId => _hubContext.Clients .Group($"user_{userId}") .SendAsync("ReceiveNotification", notification.ToMap())); await Task.WhenAll(tasks); } public async Task SendNotificationToAllUsers(NotificationModel notification) { // Save to database first _context.NotificationModels.Add(notification); await _context.SaveChangesAsync(); // Send to all connected clients await _hubContext.Clients.All.SendAsync("ReceiveNotification", notification.ToMap()); } // NEW METHOD: Send individual notifications to each user in the list public async Task SendNotificationToListOfUsers(IEnumerable userIds, NotificationModel notification) { var notifications = new List(); var sendTasks = new List(); foreach (var userId in userIds) { // Create a separate notification for each user var userNotification = new NotificationModel { SenderId = notification.SenderId, ReciverId = userId, // Set the specific receiver Subject = notification.Subject, Content = notification.Content, Action = notification.Action, ActionId = notification.ActionId, LogUrl = notification.LogUrl, Status = notification.Status, Timestmp = DateTime.UtcNow }; notifications.Add(userNotification); // Prepare SignalR send task var sendTask = _hubContext.Clients .Group($"user_{userId}") .SendAsync("ReceiveNotification", userNotification.ToMap()); sendTasks.Add(sendTask); } // Save all notifications to database _context.NotificationModels.AddRange(notifications); await _context.SaveChangesAsync(); // Send all notifications via SignalR await Task.WhenAll(sendTasks); } } }