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

namespace Application.Features.Admin.Banner.Item.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 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)
        {
            if (img.DesktopImage != null)
            {
                fileStorage.DeleteByUrl(img.DesktopImage);
            }

            if (img.MobileImage != null)
            {
                fileStorage.DeleteByUrl(img.MobileImage);
            }
        }

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