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.Preview;

public class SetPreviewCommand : IRequest<Unit>
{
    public Guid TitleId { get; set; }
    public MediaInfoType Type { get; set; }
    public string? ContentType { get; set; }
    public Stream? Data { get; set; }
    public string? Url { get; set; }
}

public class SetPreviewCommandHandler(IAnimeTitleGateway titleGateway, MediaInfoService mediaInfoService) : IRequestHandler<SetPreviewCommand, Unit>
{
    public async Task<Unit> Handle(SetPreviewCommand request, CancellationToken cancellationToken)
    {
        var title = await titleGateway.GetById(request.TitleId);
        var (objectId, contentType) = await mediaInfoService.Add(new MediaInfoService.CreateModel
        {
            Id = title.Id,
            Data = request.Data,
            Url = request.Url,
            ContentType = request.ContentType,
            Type = (Domain.Entities.MediaInfoType)request.Type,
        }, true, cancellationToken);
        title.CommonProperties.SetPreview(objectId ?? throw new Exception("Preview is not set"), (Domain.Entities.MediaInfoType)request.Type, contentType);
        await titleGateway.Update(title);
        return Unit.Value;
    }
}