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

namespace Application.Features.Admin.Forum.Board.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 hasPosts = await db.Post.AsNoTracking().AnyAsync(c => request.IDs.Contains(c.BoardID), ct);
        if (hasPosts)
        {
            throw new InvalidOperationException("게시글이 등록된 게시판은 삭제할 수 없습니다. 먼저 해당 게시글을 삭제하세요.");
        }

        // BoardGroup 카운트 감소
        var boards = await db.Board.Where(c => request.IDs.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 group in groups)
        {
            var count = boards.Count(c => c.BoardGroupID == group.ID);
            group.Boards -= (short)count;
            group.UpdatedAt = DateTime.UtcNow;
        }

        db.Board.RemoveRange(boards);
        await db.SaveChangesAsync(ct);
    }
}