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

namespace Modules.User.Application.Commands;

public class DeleteCurrentSessionCommand : IRequest<bool>
{
}

public class DeleteCurrentSessionCommandHandler(UserContext userContext, IUserGateway userGateway, IAccountGateway accountGateway) : IRequestHandler<DeleteCurrentSessionCommand, bool>
{
    public async Task<bool> Handle(DeleteCurrentSessionCommand request, CancellationToken cancellationToken)
    {
        ////var session = await accountGateway.GetAccountSessions(request.RefreshToken) ?? throw new Exception("Session was not found");
        //var user = await userGateway.Get(session.AccountId) ?? throw new Exception("User was not found");
        //if (!user.Account.DeleteSession(session.Id)) return false;
        var userInfo = await userContext.GetUserInfo(cancellationToken);
        //if (userInfo?.AccountId == null) throw new Exception("Account not found");
        if (userInfo?.AccountId == null) throw new Exception("User not found");
        var user = await userGateway.Get(userInfo.AccountId.Value) ?? throw new Exception("User was not found");
        if (userInfo.SessionId == null) throw new Exception("Active session not found");
        var session = user.Account.Sessions.FirstOrDefault(q => q.Id == userInfo.SessionId);
        if (session == null) throw new Exception("Session not found");
        if (!user.Account.DeleteSession(session.Id)) return false;
        return await accountGateway.UpdateSessions(user.Account.Id, user.Account.Sessions.Select(q => new Session
        {
            Id = q.Id,
            RefreshToken = q.RefreshToken,
            ClientInfo = new()
            {
                UserAgent = q.ClientInfo.UserAgent,
                Location = new()
                {
                    Country = q.ClientInfo.Country,
                    Region = q.ClientInfo.Region,
                }
            },
            AccountId = q.AccountId,
            ExpiredDate = q.ExpiredDate,
        }));
    }
}
