using Application.Abstractions.Data;
using SharedKernel.Storage;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Document.Delete
{
    public sealed class Handler(IAppDbContext db, IEditorImageService editorImage) : IRequestHandler<Command>
    {
        public async Task Handle(Command request, CancellationToken ct)
        {
            if (request.IDs is null || request.IDs.Length == 0)
            {
                return;
            }

            var contents = await db.Document.Where(c => request.IDs.Contains(c.ID)).Select(c => c.Content).ToListAsync(ct);

            foreach (var content in contents)
            {
                await editorImage.CleanupByContentAsync(content, ct);
            }

            await db.Document.Where(c => request.IDs.Contains(c.ID)).ExecuteDeleteAsync(ct);
        }
    }
}