using MediatR;
using Modules.Library.Application.Gateways;
using Modules.Library.Application.Services;
using Modules.Library.Domain.Entities.MediaContent.Items.Anime;

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

public class AddEpisodeCommand : IRequest<Guid>
{
    public Guid TitleId { get; init; }

    public IEnumerable<Name> Names { get; init; } = [];
    public MediaInfo? Preview { get; set; }
    public IEnumerable<Description> Descriptions { get; init; } = [];
    public IEnumerable<Genre> Genres { get; init; } = [];
    public List<MediaInfo> RelatedContent { get; init; } = [];

    public DateTimeOffset? AnnouncementDate { get; init; }
    public DateTimeOffset? EstimatedReleaseDate { get; init; }
    public DateTimeOffset ReleaseDate { get; init; }

    public int? Number { get; init; }
    public Models.AnimeEpisodeType Type { get; init; }
    
    public TimeSpan? Duration { get; init; }
}

public class AddEpisodeCommandHandler(IAnimeTitleGateway titleGateway, IAnimeEpisodeGateway episodeGateway, ILanguageGateway languageGateway,
    IGenreGateway genreGateway, MediaInfoService mediaInfoService) : IRequestHandler<AddEpisodeCommand, Guid>
{
    public async Task<Guid> Handle(AddEpisodeCommand request, CancellationToken cancellationToken)
    {
        var title = await titleGateway.GetById(request.TitleId);
        //if (!request.Names.Any()) throw new Exception("No names");

        var languages = (await languageGateway.GetLanguageByIds(request.Names.Select(q => q.LanguageId).Distinct())).ToArray();
        var genres = (await genreGateway.GetGenreByIds(request.Genres.Select(q => q.GenreId).Distinct())).ToArray();

        //var episode = title.AddEpisode((Domain.Entities.MediaContent.Items.Anime.AnimeEpisodeType)request.Type);
        //replace type by tags
        //var episodeType = request.Type switch
        //{
        //    Models.AnimeEpisodeType.Regilar => Domain.Entities.MediaContent.Items.Anime.AnimeEpisodeType.Regilar,
        //    Models.AnimeEpisodeType.Ova => Domain.Entities.MediaContent.Items.Anime.AnimeEpisodeType.Ova,
        //    Models.AnimeEpisodeType.FullLength => Domain.Entities.MediaContent.Items.Anime.AnimeEpisodeType.FullLength,
        //    _ => throw new NotImplementedException()
        //};
        var episode = title.AddEpisode((AnimeEpisodeType)request.Type, request.Names.Select(q =>
            new Domain.Entities.MediaContent.CommonProperties.NameItem((Domain.Entities.MediaContent.CommonProperties.NameType)q.NameType,
            languages.First(x => x.Id == q.LanguageId).Id, q.Value)), request.Number, request.Duration);
        //var language = await languageGateway.GetLanguageById(request.NameLanguageId);
        foreach (var name in request.Names)
        {
            var languageId = languages.First(x => x.Id == name.LanguageId).Id;
            var type = (Domain.Entities.MediaContent.CommonProperties.NameType)name.NameType;
            episode.CommonProperties.AddName(type, languageId, name.Value);
        }

        if (request.Descriptions.Any())
        {
            foreach (var description in request.Descriptions)
            {
                var languageId = languages.First(q => q.Id == description.LanguageId).Id;
                if (description.IsOriginal) episode.CommonProperties.AddOriginalDescription(languageId, description.Value);
                else episode.CommonProperties.AddNotOriginalDescription(languageId, description.Value);
            }
        }
        if (request.Genres.Any())
        {
            foreach (var genre in request.Genres)
            {
                var genreId = genres.First(q => q.Id == genre.GenreId).Id;
                episode.CommonProperties.AddGenre(genreId, genre.Proportion);
            }
        }
        if (request.RelatedContent.Any())
        {
            foreach (var relatedContentItem in request.RelatedContent)
            {
                //add model
                var (objectId, contentType) = await mediaInfoService.Add(new MediaInfoService.CreateModel
                {
                    Data = relatedContentItem.Data,
                    Url = relatedContentItem.Url,
                    ContentType = relatedContentItem.ContentType,
                    Type = (Domain.Entities.MediaInfoType)relatedContentItem.Type,
                }, false, cancellationToken);

                //objectId
                episode.CommonProperties.AddRelatedContent(objectId, (Domain.Entities.MediaInfoType)relatedContentItem.Type, contentType);
            }
        }

        episode.CommonProperties.SetAnnouncementDate(request.AnnouncementDate);
        episode.CommonProperties.SetEstimatedReleaseDate(request.EstimatedReleaseDate);
        episode.CommonProperties.SetReleaseDate(request.ReleaseDate);
        var animeEpisodeId = await episodeGateway.Create(title.Id, null, episode);
        if (request.Preview != null)
        {
            title = await titleGateway.GetById(title.Id);
            episode = title.Items.OfType<AnimeEpisode>().First(q => q.Id == animeEpisodeId);
            var (objectId, contentType) = await mediaInfoService.Add(new MediaInfoService.CreateModel
            {
                Id = animeEpisodeId,
                Data = request.Preview.Data,
                Url = request.Preview.Url,
                ContentType = request.Preview.ContentType,
                Type = (Domain.Entities.MediaInfoType)request.Preview.Type,
            }, true, cancellationToken);
            episode.CommonProperties.SetPreview(objectId, (Domain.Entities.MediaInfoType)request.Preview.Type, contentType);
            await episodeGateway.Update(title.Id, null, episode);
        }
        //return await titleGateway.Create(animeTitle);
        return animeEpisodeId;
    }
}