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

namespace Modules.Rating.Api.Querirs;

public class ObjectRatingQuery : IRequest<Models.Vote?>
{
    public Guid ObjectId { get; set; } = default!;
    public Guid? SubjectId { get; set; }
}

public class ObjectRatingQueryHandler(RatingRepository repository) : IRequestHandler<ObjectRatingQuery, Models.Vote?>
{
    public async Task<Models.Vote?> Handle(ObjectRatingQuery request, CancellationToken cancellationToken)
    {
        var rate = await repository.GetAverageObjectRating(request.ObjectId);

        var subjectRate = request.SubjectId.HasValue
            ? await repository.GetFirstOrDefaultWhere(q => q.ObjectId == request.ObjectId &&
                q.SubjectId == (request.SubjectId.HasValue ? request.SubjectId.Value : q.SubjectId))
            : null;

        return rate.HasValue
            ? new Models.Vote
            {
                ObjectId = request.ObjectId,
                //SubjectId = request.SubjectId,
                ObjectRatePercentage = (ushort)Math.Round((decimal)rate, 0),
                SubjectRatePercentage = subjectRate?.RatingPercentage,
            }
            : null;
    }
}