using MediatR;
using Modules.Library.Application.Commands.CommonModels;
using Modules.Library.Application.Gateways;
using Modules.Library.Application.Services;

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

public class DeleteRelatedContentCommand : IRequest<Unit>
{
    public Guid TitleId { get; set; }
    public MediaInfoType Type { get; set; }
    public string ObjectId { get; set; } = default!;
    public string ContentType { get; set; } = default!;
}

public class DeleteRelatedContentCommandHandler(IAnimeTitleGateway titleGateway, MediaInfoService mediaInfoService) : IRequestHandler<DeleteRelatedContentCommand, Unit>
{
    public async Task<Unit> Handle(DeleteRelatedContentCommand request, CancellationToken cancellationToken)
    {
        var title = await titleGateway.GetById(request.TitleId);
        if (!title.CommonProperties.RelatedContent.Any(q => q.ObjectId == request.ObjectId))
        {
            throw new Exception("related content not found");
        }
        var mediaInfo = new Domain.Entities.MediaInfo(request.ObjectId, (Domain.Entities.MediaInfoType)request.Type, request.ContentType);
        var deleted = await mediaInfoService.Remove(request.ObjectId, true, cancellationToken);
        if (deleted)
        {
            title.CommonProperties.RemoveRelatedContent(mediaInfo);
            await titleGateway.Update(title);
        }
        return Unit.Value;
    }
}