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 AddRelatedContentCommand : IRequest<Unit>
{
    public Guid TitleId { get; set; }
    public MediaInfoType Type { get; set; }
    public Stream? Data { get; set; }
    public string? ContentType { get; set; }
    public string? Url { get; set; }
}

public class AddRelatedContentCommandHandler(IAnimeTitleGateway titleGateway, MediaInfoService mediaInfoService) : IRequestHandler<AddRelatedContentCommand, Unit>
{
    public async Task<Unit> Handle(AddRelatedContentCommand request, CancellationToken cancellationToken)
    {
        var title = await titleGateway.GetById(request.TitleId);

        var (objectId, contentType) = await mediaInfoService.Add(new MediaInfoService.CreateModel
        {
            Data = request.Data,
            Url = request.Url,
            ContentType = request.ContentType,
            Type = (Domain.Entities.MediaInfoType)request.Type,
        }, false, cancellationToken);
        title.CommonProperties.AddRelatedContent(objectId ?? throw new Exception("Related content is not set"), (Domain.Entities.MediaInfoType)request.Type, contentType);
        await titleGateway.Update(title);
        return Unit.Value;
    }
}