using MediatR;
using Modules.Library.Application.Gateways;
using Modules.Rating.Api.Commands;
using Modules.User.Application;

namespace Modules.Library.Application.Commands.Anime.Episode;

public class VoteTitleCommand : IRequest<Unit>
{
    public Guid TitleId { get; set; }
    public Guid SeasonId { get; init; }
    public Guid EpisodeId { get; init; }
    public ushort RatingPercentage { get; set; }
}

public class VoteTitleCommandHandler(IAnimeTitleGateway titleGateway, UserContext userContext, IMediator mediator) : IRequestHandler<VoteTitleCommand, Unit>
{
    public async Task<Unit> Handle(VoteTitleCommand request, CancellationToken cancellationToken)
    {
        var user = await userContext.GetUserInfo(cancellationToken);
        if (!user.IsAuthenticated || (!user.Id.HasValue || user.Id == Guid.Empty))
        {
            throw new Exception("User is not authenticated");
        }
        var subjectId = user.Id.Value;
        var title = await titleGateway.GetById(request.TitleId);
        if (!title.Deleted)
        {
            await mediator.Send(new VoteForObjectCommand
            {
                ObjectId = title.Id,
                SubjectId = subjectId,
                RatingPercentage = request.RatingPercentage
            }, cancellationToken);
        }
        return Unit.Value;
    }
}