using Application.Abstractions.Messaging;
using Application.Abstractions.Data;
using Domain.Entities.Wallets.ValueObject;
using Microsoft.EntityFrameworkCore;

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

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

        if (tx is null)
        {
            throw new KeyNotFoundException("거래 내역을 찾을 수 없습니다.");
        }

        var wallet = tx.Wallet;

        return new Response
        {
            ID = tx.ID,
            WalletKey = tx.WalletKey,
            WalletID = wallet.ID,
            MemberID = wallet.MemberID,
            MemberEmail = wallet.Member.Email,
            MemberName = wallet.Member.Name,
            WalletBalance = (long)wallet.GetTotalAvailable().Value,
            WalletDonationBalance = (long)wallet.GetBalance(WalletBalanceType.Donation).Value,
            TxType = tx.TxType,
            BalanceType = tx.BalanceType,
            Amount = (long)tx.Amount.Value,
            BalanceAfter = (long)tx.BalanceAfter.Value,
            Reason = tx.Reason,
            RefID = tx.RefID,
            UserID = tx.UserID,
            Memo = tx.Memo,
            CreatedAt = tx.CreatedAt
        };
    }
}