namespace Modules.Library.Core.Domain.MediaContent.Items.Anime;

public class AnimeSeason : AnimeItem, IContainer<AnimeItem>
{
    public int? Number { get; set; }
    public string Director { get; protected set; } = default!;
    public string OriginCountry { get; protected set; } = default!;

    protected List<AnimeItem> _items = [];
    public IReadOnlyCollection<AnimeItem> Items => _items.AsReadOnly();

    public void AddEpisode(AnimeEpisode episode)
    {
        var lastOrder = _items.OrderByDescending(q => q.Order).FirstOrDefault()?.Order;
        _items.Add(episode);
        episode.SetOrder(lastOrder.HasValue ? lastOrder.Value + 1 : 0);
        CheckIfCompleted();
    }

    public void AddEpisodeAsVariant(AnimeEpisode episode, uint order)
    {
        var lastVariant = _items.OrderByDescending(q => q.Variant).FirstOrDefault(q => q.Order == order)?.Variant ??
            throw new Exception($"Could not find episode with order [{order}]");
        
        _items.Add(episode);
        episode.SetOrder(order);
        //episode.SetVariant(lastVariant.HasValue ? lastVariant.Value + 1 : 0);
        episode.SetVariant(lastVariant + 1);
        CheckIfCompleted();
    }

    private void CheckIfCompleted()
    {
        var itemsQuery = Items.AsQueryable();
        var unreleasedEpisodesAreExists = itemsQuery
            .Any(q => !q.CommonProperties.ReleaseDate.HasValue);
        var lastEpisodeReleaseDate = itemsQuery
            .OrderByDescending(q => q.CommonProperties.ReleaseDate)
            .FirstOrDefault()?.CommonProperties.ReleaseDate;
        //return unreleasedEpisodesAreExists || lastEpisodeReleaseDate - DateTime.UtcNow > expirePeriod;
        if (unreleasedEpisodesAreExists || lastEpisodeReleaseDate >= (DateTime.UtcNow - ExpirationTime)) SetNotCompleted();
        else SetCompleted();
    }
}