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

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

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

            return new Response(
                coin.ID,
                coin.Symbol,
                [..coin.CoinMarket.Select(m => m.Market)],
                coin.KorName,
                coin.EngName,
                coin.LogoImage,
                coin.Description,
                coin.ContractAddress,
                coin.WebsiteUrl,
                coin.WhitepaperUrl,
                coin.TwitterUrl,
                coin.TelegramUrl,
                coin.IsActive,
                coin.IsWarning,
                coin.IsNew,
                coin.IsDelisted,
                [..coin.CoinCategoryMap.Select(m => m.CategoryID)],
                coin.UpdatedAt,
                coin.CreatedAt
            );
        }
    }
}