using Application.Abstractions.Messaging;
﻿using Application.Abstractions.Data;
using Application.Abstractions.Cache;
using SharedKernel.Storage;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Admin.Document.Delete
{
    public sealed class Handler(IAppDbContext db, IEditorImageService editorImage, ICacheService cache) : ICommandHandler<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);
            await cache.RemoveByPrefixAsync("document:", ct);
        }
    }
}