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

namespace Modules.User.Application.Commands.User.Access;

public class GrantPermissionToUserCommand : IRequest<Unit>
{ 
    public Guid AccountId { get; set; }
    public int PermissionId { get; set; }
    public string? GrantReason { get; set; }
}

public class GrantPermissionToUserCommandHandler(UserContext userContext, IUserRepository userRepository,
    IPermissionRepository permissionRepository, IUnitOfWork unitOfWork) : IRequestHandler<GrantPermissionToUserCommand, Unit>
{
    public async Task<Unit> Handle(GrantPermissionToUserCommand request, CancellationToken cancellationToken)
    {
        var issuerId = userContext.GetAccountId();
        if (!issuerId.HasValue) return Unit.Value;
        //TODO: check privilegiess and ban status
        //TODO: if (user == null) throw new UserNotFoundException(); //"User not found"
        var user = await userRepository.GetByAccountIdAsync(request.AccountId, cancellationToken);
        if (user == null) return Unit.Value;
        //TODO: if (user == null) throw new UserNotFoundException(); //"User not found"
        if (await permissionRepository.GetAsync(request.PermissionId, cancellationToken) is null)
            return Unit.Value;
            //TODO: throw new KeyNotFoundException("Permission not found.");

        user.Account.GrantPermission(request.PermissionId, DateTime.UtcNow, issuerId.Value, request.GrantReason);
        await userRepository.SaveAsync(user, cancellationToken);
        await unitOfWork.SaveChangesAsync(cancellationToken);
        return Unit.Value;
    }
}