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

namespace MyHN.Application
{
  public class VoteForLinkCommandHandler : IRequestHandler<VoteForLinkCommand>
  {
    private readonly ILinkRepository _repository;
    private readonly IUserProvider _userProvider;

    public VoteForLinkCommandHandler(ILinkRepository repository, IUserProvider userProvider)
    {
      _repository = repository;
      _userProvider = userProvider;
    }

    public async Task<Unit> Handle(VoteForLinkCommand request, CancellationToken cancellationToken)
    {
      var link = _repository.GetById(request.LinkId);
      var user = _userProvider.GetCurrentUserId();

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

      await _repository.UpdateAsync(link);

      return Unit.Value;
    }
  }
}