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

namespace Application.Features.Admin.Forum.Trash.Comment.Restore;

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);

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

        // Post 댓글 카운트 복원
        var postCommentCounts = comments.GroupBy(c => c.PostID).ToDictionary(g => g.Key, g => g.Count());
        var posts = await db.Post.Where(p => postCommentCounts.Keys.Contains(p.ID)).ToListAsync(ct);

        foreach (var post in posts)
        {
            post.Comments += postCommentCounts[post.ID];
            post.UpdatedAt = DateTime.UtcNow;
        }

        // Board 댓글 카운트 복원
        var boardCommentCounts = comments.GroupBy(c => c.BoardID).ToDictionary(g => g.Key, g => g.Count());
        var boards = await db.Board.Where(b => boardCommentCounts.Keys.Contains(b.ID)).ToListAsync(ct);

        foreach (var board in boards)
        {
            board.Comments += boardCommentCounts[board.ID];
            board.UpdatedAt = DateTime.UtcNow;
        }

        // MemberStats 댓글 수 복원
        var memberCommentCounts = comments.GroupBy(c => c.MemberID).ToDictionary(g => g.Key, g => g.Count());
        var memberStats = await db.MemberStats.Where(x => memberCommentCounts.Keys.Contains(x.MemberID)).ToListAsync(ct);

        foreach (var stats in memberStats)
        {
            stats.CommentCount += memberCommentCounts[stats.MemberID];
        }

        await db.SaveChangesAsync(ct);
    }
}