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

namespace Modules.User.Application.Commands;

public class DeleteSessionCommand : IRequest<bool>
{
    public Guid AccountId { get; set; } = default!;
    public Guid SessionId { get; set; } = default!;
}

public class DeleteSessionCommandHandler(IUserGateway userGateway, IAccountGateway accountGateway) : IRequestHandler<DeleteSessionCommand, bool>
{
    public async Task<bool> Handle(DeleteSessionCommand request, CancellationToken cancellationToken)
    {
        //var user = await userGateway.Get(request.AccountId) ?? throw new UserNotFoundException();
        var user = await userGateway.Get(request.AccountId) ?? throw new Exception("User was not found");
        if (!user.Account.DeleteSession(request.SessionId)) 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,
        }));
    }
}