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

namespace Application.Features.Admin.Forum.Post.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 posts = await db.Post.Where(c => request.IDs.Contains(c.ID) && !c.IsDeleted).ToListAsync(ct);
        if (posts.Count == 0)
        {
            return;
        }

        foreach (var post in posts)
        {
            post.IsDeleted = true;
            post.DeletedAt = DateTime.UtcNow;
        }

        // Board 카운트 감소
        var boardIDs = posts.Select(c => c.BoardID).Distinct().ToList();
        var boards = await db.Board.Where(c => boardIDs.Contains(c.ID)).ToListAsync(ct);
        var groupIDs = boards.Select(c => c.BoardGroupID).Distinct().ToList();
        var groups = await db.BoardGroup.Where(c => groupIDs.Contains(c.ID)).ToListAsync(ct);

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

        foreach (var group in groups)
        {
            var relatedBoards = boards.Where(b => b.BoardGroupID == group.ID).Select(b => b.ID).ToList();
            var count = posts.Count(c => relatedBoards.Contains(c.BoardID));
            group.Posts -= count;
            group.UpdatedAt = DateTime.UtcNow;
        }

        await db.SaveChangesAsync(ct);
    }
}