using MediatR;
using Modules.User.Application.Models;
using Modules.User.Application.Repositories;

namespace Modules.User.Application.Queries;

public class GetUserListQuery : IRequest<PagedData<UserInfoShort>>
{
    public bool? HasAvatar { get; init; }
    public string? NickName { get; init; }
    public DateTimeOffset? LastOnlineFrom { get; init; }
    public DateTimeOffset? LastOnlineTo { get; init; }
    public bool? IsBanned { get; init; }
    public int Page { get; init; }
    public int ItemsOnPage { get; init; }
}

public class GetUserListQueryHandler(IUserQueries userQueries) : IRequestHandler<GetUserListQuery, PagedData<UserInfoShort>>
{
    public async Task<PagedData<UserInfoShort>> Handle(GetUserListQuery request, CancellationToken cancellationToken)
    {
        var now = DateTimeOffset.UtcNow;
        var users = await userQueries.GetUsersAsync(new UserListFilter
        {
            HasAvatar = request.HasAvatar,
            NickName = request.NickName,
            LastOnlineFrom = request.LastOnlineFrom,
            LastOnlineTo = request.LastOnlineTo,
            IsBanned = request.IsBanned,
            ItemsOnPage = request.ItemsOnPage,
            Page = request.Page,
        }, cancellationToken);
        foreach (var user in users.Items)
        {
            user.OnlineStatus = UserOnlineStatusDeterminant.GetOnlineStatus(user.LastOnline, now);
        }
        
        return users;
    }
}