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

namespace Application.Features.Admin.Crypto.Board.GetBoards
{
    public sealed class Handler(IAppDbContext db) : IQueryHandler<Query, Response>
    {
        public async Task<Response> Handle(Query request, CancellationToken ct)
        {
            var coin = await db.Coin.AsNoTracking().FirstOrDefaultAsync(c => c.ID == request.CoinID, ct);

            if (coin is null)
            {
                throw new KeyNotFoundException("코인을 찾을 수 없습니다.");
            }

            var allBoards = await db.Board
                .AsNoTracking()
                .Include(b => b.BoardGroup)
                .OrderBy(b => b.BoardGroup.Order)
                .ThenBy(b => b.Order)
                .Select(b => new
                {
                    b.ID,
                    b.Code,
                    b.Name,
                    GroupName = b.BoardGroup.Name,
                    b.IsActive,
                    b.CoinID
                })
                .ToListAsync(ct);

            var linked = allBoards
                .Where(b => b.CoinID == request.CoinID)
                .Select(b => new Response.Row(b.ID, b.Code, b.Name, b.GroupName, b.IsActive))
                .ToList();

            var unlinked = allBoards
                .Where(b => b.CoinID is null)
                .Select(b => new Response.Row(b.ID, b.Code, b.Name, b.GroupName, b.IsActive))
                .ToList();

            return new Response(coin.Symbol, coin.KorName, linked, unlinked);
        }
    }
}