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 AddSeasonCommand : 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; } = [];

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

    public int? Number {  get; init; }
}

public class AddSeasonCommandHandler(IAnimeTitleGateway titleGateway, IAnimeSeasonGateway seasonGateway, ILanguageGateway languageGateway,
    IGenreGateway genreGateway, MediaInfoService mediaInfoService) : IRequestHandler<AddSeasonCommand, Guid>
{
    public async Task<Guid> Handle(AddSeasonCommand 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 season = title.AddSeason(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);
        //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;
            season.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) season.CommonProperties.AddOriginalDescription(languageId, description.Value);
                else season.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;
                season.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
                season.CommonProperties.AddRelatedContent(objectId, (Domain.Entities.MediaInfoType)relatedContentItem.Type, contentType);
            }
        }

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