using System.Threading;
using System.Threading.Tasks;
using MediatR;
using MyHN.Domain;

namespace MyHN.Application
{
  public class VoteForCommentCommandHandler : IRequestHandler<VoteForCommentCommand>
  {
    private readonly ICommentRepository _repository;
    private readonly IUserProvider _userProvider;

    public VoteForCommentCommandHandler(ICommentRepository repository, IUserProvider userProvider)
    {
      _repository = repository;
      _userProvider = userProvider;
    }

    public async Task<Unit> Handle(VoteForCommentCommand request, CancellationToken cancellationToken)
    {
      var comment = _repository.GetById(request.CommentId);
      var user = _userProvider.GetCurrentUserId();

      switch (request.Direction)
      {
        case VoteType.Up:
          comment.UpvoteBy(user);
          break;
        case VoteType.Down:
          comment.DownvoteBy(user);
          break;
      }

      await _repository.UpdateAsync(comment);

      return Unit.Value;
    }
  }
}