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

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

        var commentIDs = reports.Select(c => c.CommentID).Distinct().ToList();
        var comments = await db.Comment.Where(c => commentIDs.Contains(c.ID)).ToListAsync(ct);

        foreach (var comment in comments)
        {
            var count = reports.Count(c => c.CommentID == comment.ID);
            comment.Reports -= count;
            comment.UpdatedAt = DateTime.UtcNow;
        }

        db.CommentReport.RemoveRange(reports);

        await db.SaveChangesAsync(ct);
    }
}