using MediatR;
using Modules.User.Application.Gateways;

namespace Modules.User.Application.Commands.Session;

public class DeleteAllSessionsCommand : IRequest<bool>
{
    public Guid AccountId { get; init; }
}

public class DeleteAllSessionsCommandHandler(IUserRepository userRepository, IUnitOfWork unitOfWork) : IRequestHandler<DeleteAllSessionsCommand, bool>
{
    public async Task<bool> Handle(DeleteAllSessionsCommand request, CancellationToken cancellationToken)
    {
        var user = await userRepository.GetByAccountIdAsync(request.AccountId, cancellationToken);
        if (user == null) return false;
        var allSessionIds = user.Account.Sessions.Select(q => q.Id);
        var successAll = true;
        foreach (var sessionId in allSessionIds)
        {
            var success = user.DeleteSession(sessionId);
            if (!success && successAll)
            {
                //TODO: log error
                successAll = false;
            }
        }
        
        await userRepository.SaveAsync(user, cancellationToken);
        await unitOfWork.SaveChangesAsync(cancellationToken);
        return successAll;
    }
}
