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

namespace Application.Features.Admin.Member.List.Delete;

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

        var images = await db.Member.Where(c => request.IDs.Contains(c.ID)).Select(c => new { c.Thumb, c.Icon }).ToListAsync(ct);

        foreach (var img in images)
        {
            if (!string.IsNullOrEmpty(img.Thumb))
            {
                fileStorage.DeleteByUrl(img.Thumb);
            }

            if (!string.IsNullOrEmpty(img.Icon))
            {
                fileStorage.DeleteByUrl(img.Icon);
            }
        }

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