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

namespace Application.Features.Admin.Crypto.Board.LinkBoard
{
    public sealed class Handler(IAppDbContext db) : ICommandHandler<Command>
    {
        public async Task Handle(Command request, CancellationToken ct)
        {
            if (!await db.Coin.AnyAsync(c => c.ID == request.CoinID, ct))
            {
                throw new KeyNotFoundException("코인을 찾을 수 없습니다.");
            }

            var board = await db.Board.FirstOrDefaultAsync(b => b.ID == request.BoardID, ct);

            if (board is null)
            {
                throw new KeyNotFoundException("게시판을 찾을 수 없습니다.");
            }

            if (board.CoinID is not null)
            {
                throw new InvalidOperationException("이미 다른 코인에 연결된 게시판입니다.");
            }

            board.CoinID = request.CoinID;
            await db.SaveChangesAsync(ct);
        }
    }
}