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

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

        foreach (var image in images)
        {
            fileStorage.DeleteByUrl(image.Url);
        }

        var postIDs = images.Select(c => c.PostID).Distinct().ToList();
        var posts = await db.Post.Where(c => postIDs.Contains(c.ID)).ToListAsync(ct);

        foreach (var post in posts)
        {
            var count = (byte)images.Count(c => c.PostID == post.ID);
            post.Images = (byte)Math.Max(0, post.Images - count);
            post.UpdatedAt = DateTime.UtcNow;
        }

        db.PostImage.RemoveRange(images);

        await db.SaveChangesAsync(ct);
    }
}