using MediatR;
using Modules.Rating.Api.Database.Entities;
using Modules.Rating.Api.Repositories;

namespace Modules.Rating.Api.Commands;

public class VoteForObjectCommand : IRequest<Unit>
{
    public Guid ObjectId { get; set; }
    public Guid SubjectId { get; set; }
    public ushort RatingPercentage { get; set; }

}

public class VoteForObjectCommandHandler(RatingRepository repository) : IRequestHandler<VoteForObjectCommand, Unit>
{
    public async Task<Unit> Handle(VoteForObjectCommand request, CancellationToken cancellationToken)
    {
        var vote = new Vote
        {
            ObjectId = request.ObjectId,
            SubjectId = request.SubjectId,
            RatingPercentage = request.RatingPercentage,
        };

        if (!await repository.IsVoteExists(request.ObjectId, request.SubjectId))
        {
            //await repository.AddAsync(new Rate { Key = key, RatePercentage = request.RatePercentage, });
            await repository.AddAsync(vote, cancellationToken);
        }
        else
        {
            if (!await repository.UpdateAsync(vote, cancellationToken))
            {
                throw new Exception("Vote not found");
            }
        }
        return Unit.Value;
    }
}