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

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

        // 미삭제 댓글만 카운트 감소 (소프트 삭제된 댓글은 이미 카운트가 감소됨)
        var activeComments = comments.Where(c => !c.IsDeleted).ToList();

        // Post 댓글 카운트 감소
        var postIDs = activeComments.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 = activeComments.Count(c => c.PostID == post.ID);
            post.Comments -= count;
            post.UpdatedAt = DateTime.UtcNow;
        }

        // Board 댓글 카운트 감소
        var boardIDs = activeComments.Select(c => c.BoardID).Distinct().ToList();
        var boards = await db.Board.Where(c => boardIDs.Contains(c.ID)).ToListAsync(ct);

        foreach (var board in boards)
        {
            var count = activeComments.Count(c => c.BoardID == board.ID);
            board.Comments -= count;
            board.UpdatedAt = DateTime.UtcNow;
        }

        db.Comment.RemoveRange(comments);
        await db.SaveChangesAsync(ct);
    }
}