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

namespace Application.Features.Admin.Member.Wallet.List.Get;

public sealed class Handler(IAppDbContext db) : IQueryHandler<Query, Response>
{
    public async Task<Response> Handle(Query request, CancellationToken ct)
    {
        var wallet = await db.Wallet.AsNoTracking().Include(x => x.Member).ThenInclude(m => m.MemberGrade).Include(x => x.Balances).FirstOrDefaultAsync(x => x.ID == request.Id, ct);

        if (wallet is null)
        {
            throw new KeyNotFoundException("지갑을 찾을 수 없습니다.");
        }

        return new Response
        {
            WalletID = wallet.ID,
            Balance = (long)wallet.GetTotalAvailable().Value,
            MemberID = wallet.MemberID,
            MemberEmail = wallet.Member.Email,
            GradeName = wallet.Member.MemberGrade?.KorName
        };
    }
}