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

namespace Application.Features.Admin.Forum.Board.Update;

public sealed class Handler(IAppDbContext db) : ICommandHandler<Command>
{
    public async Task Handle(Command request, CancellationToken ct)
    {
        var board = await db.Board.FirstOrDefaultAsync(x => x.ID == request.ID, ct);
        if (board is null)
        {
            throw new KeyNotFoundException("게시판을 찾을 수 없습니다.");
        }

        if (!await db.BoardGroup.AnyAsync(x => x.ID == request.BoardGroupID, ct))
        {
            throw new KeyNotFoundException("게시판 분류를 찾을 수 없습니다.");
        }

        if (board.Code != request.Code && await db.Board.AnyAsync(x => x.Code == request.Code, ct))
        {
            throw new InvalidOperationException($"`{request.Code}`는 이미 등록된 게시판 주소입니다.");
        }

        var oldGroupID = board.BoardGroupID;

        board.BoardGroupID = request.BoardGroupID;
        board.Code = request.Code;
        board.Name = request.Name;
        board.Order = request.Order;
        board.IsSearch = request.IsSearch;
        board.IsActive = request.IsActive;
        board.UpdatedAt = DateTime.UtcNow;

        // BoardGroup 변경 시 카운트 조정
        if (oldGroupID != request.BoardGroupID)
        {
            var oldGroup = await db.BoardGroup.FirstOrDefaultAsync(x => x.ID == oldGroupID, ct);
            if (oldGroup is not null)
            {
                oldGroup.Boards--;
                oldGroup.UpdatedAt = DateTime.UtcNow;
            }

            var newGroup = await db.BoardGroup.FirstOrDefaultAsync(x => x.ID == request.BoardGroupID, ct);
            if (newGroup is not null)
            {
                newGroup.Boards++;
                newGroup.UpdatedAt = DateTime.UtcNow;
            }
        }

        await db.SaveChangesAsync(ct);
    }
}