using Application.Abstractions.Data;
using Application.Abstractions.Messaging;
using Domain.Entities.Forum.ValueObject;
using Microsoft.EntityFrameworkCore;

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

        var commentIDs = reactions.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 likes = reactions.Count(c => c.CommentID == comment.ID && c.Reaction == Reaction.Like);
            var dislikes = reactions.Count(c => c.CommentID == comment.ID && c.Reaction == Reaction.Dislike);
            comment.Likes -= likes;
            comment.Dislikes -= dislikes;
            comment.UpdatedAt = DateTime.UtcNow;
        }

        db.CommentReaction.RemoveRange(reactions);

        await db.SaveChangesAsync(ct);
    }
}