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 EditRelatedContentCommand : IRequest<Unit>
{
    public Guid TitleId { get; set; }
    public MediaInfoType Type { get; set; }
    public string ObjectId { get; set; } = default!;
    public MediaInfoType? NewType { get; set; }
    public Stream? NewData { get; set; }
    public string? NewContentType { get; set; }
    public string? NewUrl { get; set; }
}

public class EditRelatedContentCommandHandler(IAnimeTitleGateway titleGateway, MediaInfoService mediaInfoService) : IRequestHandler<EditRelatedContentCommand, Unit>
{
    public async Task<Unit> Handle(EditRelatedContentCommand request, CancellationToken cancellationToken)
    {
        var title = await titleGateway.GetById(request.TitleId);
        var mediaInfo = title.CommonProperties.RelatedContent.FirstOrDefault(q => q.ObjectId == request.ObjectId) ?? throw new Exception("related content not found");
        var type = (Domain.Entities.MediaInfoType)(request.NewType ?? request.Type);
        var (objectId, contentType) = await mediaInfoService.Add(new MediaInfoService.CreateModel
        {
            Data = request.NewData,
            Url = request.NewUrl,
            ContentType = request.NewContentType,
            Type = type,
        }, false, cancellationToken);
        title.CommonProperties.EditRelatedContent(mediaInfo, objectId, (Domain.Entities.MediaInfoType?)request.NewType, contentType);
        return Unit.Value;
    }
}