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

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

        foreach (var file in files)
        {
            fileStorage.DeleteByUrl(file.Url);
        }

        var postIDs = files.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)files.Count(c => c.PostID == post.ID);
            post.Files = (byte)Math.Max(0, post.Files - count);
            post.UpdatedAt = DateTime.UtcNow;
        }

        db.PostFile.RemoveRange(files);

        await db.SaveChangesAsync(ct);
    }
}