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

namespace Application.Features.MemberGrade.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.MemberGrade.Where(c => request.IDs.Contains(c.ID)).Select(c => c.Image).ToListAsync(ct);

            foreach (var img in images)
            {
                if (img != null)
                {
                    fileStorage.DeleteByUrl(img);
                }
            }

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