using Minio.DataModel.Args;
using Minio;
using MediatR;
using System.Reactive.Linq;

namespace Modules.Media.Api.Commands;

public class DeleteObjectCommand : IRequest<bool>
{
    public string ObjectName { get; set; } = default!;
    public string BusketName { get; set; } = default!;
    public bool UseVersions { get; set; } = true;
}

public class DeleteObjectCommandHandler(IMinioClient client) : IRequestHandler<DeleteObjectCommand, bool>
{
    public async Task<bool> Handle(DeleteObjectCommand request, CancellationToken cancellationToken)
    {
        if (request.UseVersions)
        {
            var existingObjectStat = await client.StatObjectAsync(new StatObjectArgs()
                .WithBucket(request.BusketName)
                .WithObject(request.ObjectName));
            if (existingObjectStat.ETag == null) return false;

            var objectVersions = await client.ListObjectsAsync(new ListObjectsArgs()
                    .WithBucket(request.BusketName)
                    .WithPrefix(request.ObjectName)
                    .WithVersions(true)).Select(q => q.VersionId).ToList();

            var args = new RemoveObjectsArgs()
                .WithBucket(request.BusketName)
                .WithObjectAndVersions(request.ObjectName, objectVersions)
                ;
            await client.RemoveObjectsAsync(args, cancellationToken);
        }
        else
        {
            //var existingObjectStat = await client.StatObjectAsync(new StatObjectArgs()
            //    .WithBucket(request.BusketName)
            //    .WithObject(request.ObjectName));
            //if (existingObjectStat.ObjectName == null) return false;
            //var args = new RemoveObjectArgs()
            //    .WithBucket(request.BusketName)
            //    .WithObject(request.ObjectName)
            //    .
    
            //    ;
            //await client.RemoveObjectAsync(args, cancellationToken);

            ////var objects = await client.geto(new ListObjectsArgs()
            ////        .WithBucket(request.BusketName)
            ////        .WithVersions(request.ObjectName));
            ////        .WithVersions(request.ObjectName));


            //var args1 = new RemoveObjectsArgs()
            //    .WithBucket(request.BusketName)
            //    .WithObjectAndVersions(request.ObjectName, )
            //    ;
            //await client.RemoveObjectsAsync(args, cancellationToken);

            //var stat = await client.StatObjectAsync(new StatObjectArgs()
            //        .WithBucket(request.BusketName)
            //        .WithObject(request.ObjectName));
        }

        var stat = await client.StatObjectAsync(new StatObjectArgs()
                .WithBucket(request.BusketName)
                .WithObject(request.ObjectName));

        return stat.ETag == null;
    }
}