diff --git a/MiniSpace.Services.Identity/src/MiniSpace.Services.Identity.Infrastructure/Mongo/Queries/Handlers/GetOnlineUsersHandler.cs b/MiniSpace.Services.Identity/src/MiniSpace.Services.Identity.Infrastructure/Mongo/Queries/Handlers/GetOnlineUsersHandler.cs new file mode 100644 index 000000000..343a99f23 --- /dev/null +++ b/MiniSpace.Services.Identity/src/MiniSpace.Services.Identity.Infrastructure/Mongo/Queries/Handlers/GetOnlineUsersHandler.cs @@ -0,0 +1,46 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using Convey.CQRS.Queries; +using Convey.Persistence.MongoDB; +using MiniSpace.Services.Identity.Application.DTO; +using MiniSpace.Services.Identity.Application.Queries; +using MiniSpace.Services.Identity.Infrastructure.Mongo.Documents; +using MongoDB.Driver; + +namespace MiniSpace.Services.Identity.Infrastructure.Mongo.Queries.Handlers +{ + internal sealed class GetOnlineUsersHandler : IQueryHandler> + { + private readonly IMongoRepository _userRepository; + + public GetOnlineUsersHandler(IMongoRepository userRepository) + { + _userRepository = userRepository; + } + + public async Task> HandleAsync(GetOnlineUsers query) + { + var filter = Builders.Filter.Eq(u => u.IsOnline, true); + + var totalResults = await _userRepository.Collection.CountDocumentsAsync(filter); + + var totalPages = (int)Math.Ceiling(totalResults / (double)query.PageSize); + + var onlineUsers = await _userRepository.Collection + .Find(filter) + .SortByDescending(u => u.LastActive) + .Skip((query.Page - 1) * query.PageSize) + .Limit(query.PageSize) + .ToListAsync(); + + return PagedResult.Create( + onlineUsers.Select(user => user.AsDto()), + query.Page, + query.PageSize, + totalPages, + totalResults + ); + } + } +}