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

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

public class AnimeEpisodeQuery : IRequest<EpisodeView>
{
    public Guid TitleId { get; init; }
    public Guid Id { get; init; }
}

public class AnimeEpisodeQueryHandler(IAnimeTitleGateway titleGateway, IAnimeSeasonGateway seasonGateway,
    IAnimeEpisodeGateway episodeGateway, UserContext userContext, IMediator mediator) : IRequestHandler<AnimeEpisodeQuery, EpisodeView>
{
    public async Task<EpisodeView> Handle(AnimeEpisodeQuery request, CancellationToken cancellationToken)
    {
        var title = await titleGateway.GetDetail(request.TitleId, cancellationToken);
        var season = await seasonGateway.GetDetail(request.TitleId, request.Id, cancellationToken);
        var user = await userContext.GetUserInfo(cancellationToken);
        var titleRating = await mediator.Send(new ObjectRatingQuery { ObjectId = request.Id, SubjectId = user.Id, }, cancellationToken);
        season.Rating = titleRating?.ObjectRatePercentage;
        season.MyRating = titleRating?.SubjectRatePercentage;
        // var titleViews = await mediator.Send(new ObjectRatingQuery { ObjectId = request.Id, SubjectId = user.Id, }, cancellationToken);
        season.Views = 0; //titleViews?.Count;
        season.MyViews = 0; //titleViews?.UserViewsCount;
        season.LastViewPercentage = null; //0;

        foreach (var episode in  season.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;
        }
        
        return new SeasonView
        {
            TitleId = title.Id,
            TitleNames = title.CommonProperties.Names,
            Season = season,
        };
    }
}

public class SeasonView
{
    public Guid TitleId { get; set; }
    public IEnumerable<Models.NameItem> TitleNames { get; set; } = [];
    
    public required Models.Anime.Season Season { get; set; }
}