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 UnvoteTitleCommand : IRequest<Unit>
{
    public Guid TitleId { get; init; }
}

public class UnvoteEpisodeCommandHandler(IAnimeTitleGateway titleGateway, UserContext userContext, IMediator mediator) : IRequestHandler<UnvoteTitleCommand, Unit>
{
    public async Task<Unit> Handle(UnvoteTitleCommand 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, cancellationToken);
        if (!title.Deleted)
        {
            await mediator.Send(new UnrateObjectCommand { ObjectId = title.Id, SubjectId = subjectId }, cancellationToken);
        }
        return Unit.Value;
    }
}