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

namespace Application.Features.Api.Member.Wallet.GetMy;

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(w => w.Balances).FirstOrDefaultAsync(w => w.MemberID == request.MemberID, ct);

        if (wallet is null)
        {
            return null;
        }

        return new Response
        {
            ID = wallet.ID,
            WalletKey = wallet.WalletKey,
            MemberID = wallet.MemberID,
            Balance = (long)wallet.GetTotalAvailable().Value,
            Balances = [..wallet.Balances.Select(b => new Response.BalanceRow
            {
                Type = b.Type.ToString(),
                Amount = (long)b.Amount.Value
            })],
            CreatedAt = wallet.CreatedAt,
            UpdatedAt = wallet.UpdatedAt
        };
    }
}