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

namespace Modules.Library.Application.Commands.Anime.Episode.Properties.RelatedContent;

public class EditRelatedContentCommand : IRequest<Unit>
{
    public Guid TitleId { get; set; }
    public Guid SeasonId { get; set; }
    public Guid EpisodeId { get; set; }
    public MediaInfoType Type { get; set; }
    public string Url { get; set; } = default!;
    public string ContentType { get; set; } = default!;
    public MediaInfoType NewType { get; set; }
    public string NewUrl { get; set; } = default!;
    public string NewContentType { get; set; } = default!;

}

public class EditRelatedContentCommandHandler(IAnimeTitleGateway titleGateway) : IRequestHandler<EditRelatedContentCommand, Unit>
{
    public async Task<Unit> Handle(EditRelatedContentCommand request, CancellationToken cancellationToken)
    {
        var title = await titleGateway.GetById(request.TitleId);
        var mediaInfo = new Domain.Entities.MediaInfo(request.Url, (Domain.Entities.MediaInfoType)request.Type, request.ContentType);
        var season = title.Items.OfType<AnimeSeason>().FirstOrDefault(q => q.Id == request.SeasonId) ??
            throw new Exception("Season not found");
        var episode = season.Episodes.FirstOrDefault(q => q.Id == request.EpisodeId) ??
            throw new Exception("Episode not found");
        episode.CommonProperties.EditRelatedContent(mediaInfo, request.NewUrl, (Domain.Entities.MediaInfoType)request.NewType, request.NewContentType);
        return Unit.Value;
    }
}