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

namespace Application.Features.Admin.Crypto.List.Delete
{
    public sealed class Handler(IAppDbContext db, IFileStorage fileStorage, ICacheService cache) : ICommandHandler<Command>
    {
        public async Task Handle(Command request, CancellationToken ct)
        {
            if (request.IDs is null || request.IDs.Length == 0)
            {
                return;
            }

            var logos = await db.Coin.Where(c => request.IDs.Contains(c.ID)).Select(c => c.LogoImage).ToListAsync(ct);

            foreach (var logo in logos)
            {
                if (logo != null)
                {
                    fileStorage.DeleteByUrl(logo);
                }
            }

            await db.Coin.Where(c => request.IDs.Contains(c.ID)).ExecuteDeleteAsync(ct);
            await cache.RemoveByPrefixAsync("crypto:", ct);
        }
    }
}