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

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

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

public class AssignRoleToUserCommandHandler(UserContext userContext, IUserRepository userRepository,
    IRoleRepository roleRepository, IUnitOfWork unitOfWork) : IRequestHandler<AssignRoleToUserCommand, Unit>
{
    public async Task<Unit> Handle(AssignRoleToUserCommand 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 roleRepository.GetAsync(request.RoleId, cancellationToken) is null)
            return Unit.Value;
            //TODO: throw new KeyNotFoundException("Role not found.");

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