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

namespace Application.Features.Admin.Popup.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 < 1)
        {
            return;
        }

        var list = await db.Popup.Where(x => request.IDs.Contains(x.ID)).ToListAsync(ct);
        if (list.Count < 1)
        {
            return;
        }

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

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

        db.Popup.RemoveRange(list);

        await db.SaveChangesAsync(ct);
        await cache.RemoveByPrefixAsync("popup:", ct);
    }
}