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

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

public sealed class Handler(IAppDbContext db) : ICommandHandler<Command>
{
    public async Task Handle(Command request, CancellationToken ct)
    {
        if (!await db.BoardGroup.AnyAsync(x => x.ID == request.BoardGroupID, ct))
        {
            throw new KeyNotFoundException("게시판 분류를 찾을 수 없습니다.");
        }

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

        var board = new Domain.Entities.Forum.Boards.Board
        {
            BoardGroupID = request.BoardGroupID,
            Code = request.Code,
            Name = request.Name,
            Order = request.Order,
            IsSearch = request.IsSearch,
            IsActive = request.IsActive
        };

        await db.Board.AddAsync(board, ct);
        await db.SaveChangesAsync(ct);

        // BoardGroup의 Boards 카운트 증가
        var boardGroup = await db.BoardGroup.FirstOrDefaultAsync(x => x.ID == request.BoardGroupID, ct);
        if (boardGroup is not null)
        {
            boardGroup.Boards++;
            boardGroup.UpdatedAt = DateTime.UtcNow;
            await db.SaveChangesAsync(ct);
        }
    }
}