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

namespace Modules.User.Application.Queries;

public class GetAccountSessionsQuery : IRequest<IEnumerable<Models.Session>>
{
}

public class GetAccountSessionsQueryHandler(UserContext userContext, IUserQueries userQueries) : IRequestHandler<GetAccountSessionsQuery, IEnumerable<Models.Session>>
{
    public async Task<IEnumerable<Models.Session>> Handle(GetAccountSessionsQuery request, CancellationToken cancellationToken)
    {
        var accountId = userContext.GetAccountId();
        if (!accountId.HasValue) return [];
        //TODO: if (!accountId.HasValue) throw new UnauthorizedAccessException("AccountId not found");

        var sessionId = userContext.GetSessionId();
        var now = DateTimeOffset.UtcNow;
        var sessions = await userQueries.GetAccountSessionsAsync(accountId.Value, sessionId, cancellationToken);
        foreach (var session in sessions)
        {
            session.OnlineStatus = UserOnlineStatusDeterminant.GetOnlineStatus(session.LastOnline, now);
        }
        return sessions;
    }
}