using MediatR;
using Minio;
using Minio.DataModel.Args;
using Modules.Media.Api.Models;

namespace Modules.Media.Api.Queries;

public class GetObjectQuery : IRequest<ObjectResult?>
{
    public string BusketName { get; set; } = default!;
    public string ObjectName { get; set; } = default!;
}

public class GetObjectQueryHandler(IMinioClient client) : IRequestHandler<GetObjectQuery, ObjectResult?>
{
    public async Task<ObjectResult?> Handle(GetObjectQuery request, CancellationToken cancellationToken)
    {
        var stream = new MemoryStream();
        var args = new GetObjectArgs()
            .WithBucket(request.BusketName)
            .WithObject(request.ObjectName)
            .WithCallbackStream((s) =>
            {
                s.CopyTo(stream);
            });
        //.WithCallbackStream((stream) =>
        //{
        //    stream.CopyTo(Console.OpenStandardOutput());
        //});
        try
        {
            var getObjectResult = await client.GetObjectAsync(args, cancellationToken);
            stream.Seek(0, SeekOrigin.Begin);
            return new ObjectResult
            {
                ObjectName = getObjectResult.ObjectName,
                ContentType = getObjectResult.ContentType,
                Data = stream,
            };
        }
        catch (Minio.Exceptions.ObjectNotFoundException)
        {
            return null;
        }
    }
}