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

namespace Application.Features.Admin.Forum.PostReport.Delete;

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

        var reports = await db.PostReport.Where(c => request.IDs.Contains(c.ID)).ToListAsync(ct);

        var postIDs = reports.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 = reports.Count(c => c.PostID == post.ID);
            post.Reports -= count;
            post.UpdatedAt = DateTime.UtcNow;
        }

        db.PostReport.RemoveRange(reports);

        await db.SaveChangesAsync(ct);
    }
}