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

namespace Modules.Rating.Api.Querirs;

public class ObjectRatingListQuery : IRequest<List<Models.Vote>>
{
    public Guid? SubjectId { get; set; }
    public IEnumerable<Guid> ObjectIds { get; set; } = [];
}

public class ObjectRatingListQueryHandler(RatingRepository repository) : IRequestHandler<ObjectRatingListQuery, List<Models.Vote>>
{
    public async Task<List<Models.Vote>> Handle(ObjectRatingListQuery request, CancellationToken cancellationToken)
    {
        if (request.ObjectIds.Count() == 0) return [];
        var rates = await repository.GetVotes(request.ObjectIds, request.SubjectId);
        return rates.Select(q => new Models.Vote
        {
            ObjectId = q.ObjectId,
            ObjectRatePercentage = (ushort)Math.Round((decimal)q.Rate, 0),
            SubjectRatePercentage = q.SubjectRate.HasValue ? Convert.ToUInt16(q.SubjectRate) : null,
        }).ToList();
    }
}