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

namespace Application.Features.Banner.Item.Delete;

public sealed class Handler(IAppDbContext db, IFileStorage fileStorage) : IRequestHandler<Command>
{
    public async Task Handle(Command request, CancellationToken ct)
    {
        if (request.IDs is null || request.IDs.Length == 0)
        {
            return;
        }

        var images = await db.BannerItem.Where(c => request.IDs.Contains(c.ID)).Select(c => new { c.DesktopImage, c.MobileImage }).ToListAsync(ct);

        foreach (var img in images)
        {
            fileStorage.DeleteByUrl(img.DesktopImage);
            fileStorage.DeleteByUrl(img.MobileImage);
        }

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