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) && !c.IsDeleted).ToListAsync(ct);
        if (comments.Count == 0)
        {
            return;
        }

        foreach (var comment in comments)
        {
            comment.IsDeleted = true;
            comment.DeletedAt = DateTime.UtcNow;
        }

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

        // Board 댓글 카운트 감소
        var boardIDs = comments.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 = comments.Count(c => c.BoardID == board.ID);
            board.Comments -= count;
            board.UpdatedAt = DateTime.UtcNow;
        }

        await db.SaveChangesAsync(ct);
    }
}