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

namespace Modules.Library.Application.Queries.Anime.AnimeTitle;

public class AnimeTitleQuery : IRequest<Models.Anime.Title>
{
    public Guid Id { get; init; }
}

public class AnimeTitleQueryHandler(IAnimeTitleGateway titleGateway, UserContext userContext, IMediator mediator) : IRequestHandler<AnimeTitleQuery, Models.Anime.Title>
{
    public async Task<Models.Anime.Title> Handle(AnimeTitleQuery request, CancellationToken cancellationToken)
    {
        var title = await titleGateway.GetDetail(request.Id, cancellationToken);
        var user = await userContext.GetUserInfo(cancellationToken);
        var titleRating = await mediator.Send(new ObjectRatingQuery { ObjectId = request.Id, SubjectId = user.Id, }, cancellationToken);
        title.Rating = titleRating?.ObjectRatePercentage;
        title.MyRating = titleRating?.SubjectRatePercentage;
        // var titleViews = await mediator.Send(new ObjectRatingQuery { ObjectId = request.Id, SubjectId = user.Id, }, cancellationToken);
        title.Views = 0; //titleViews?.Count;
        title.MyViews = 0; //titleViews?.UserViewsCount;
        title.LastViewPercentage = null; //0;

        var seasons = title.Items.OfType<Modules.Library.Application.Models.Anime.Season>().ToList();
        var episodes = title.Items.OfType<Modules.Library.Application.Models.Anime.Episode>()
            .Union(seasons.SelectMany(q => q.Episodes));

        foreach (var episode in  episodes)
        {
            var rating = await mediator.Send(new ObjectRatingQuery { ObjectId = episode.Id, SubjectId = user.Id, }, cancellationToken);
            episode.Rating = rating?.ObjectRatePercentage;
            episode.MyRating = rating?.ObjectRatePercentage;
            episode.ViewsCount = 0;
            episode.MyViewsCount = 0;
            episode.LastViewPercentage = null;
        }
        
        foreach (var season in  seasons)
        {
            var rating = await mediator.Send(new ObjectRatingQuery { ObjectId = season.Id, SubjectId = user.Id, }, cancellationToken);
            season.Rating = rating?.ObjectRatePercentage;
            season.MyRating = rating?.ObjectRatePercentage;
            season.ViewsCount = 0;
            season.MyViewsCount = 0;
            season.LastViewPercentage = null;
        }
        
        return title;
    }
}