using AdsBillingService.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace AdsBillingService.API.Application.Queries;

/// <summary>
/// EN: Query to get billing account balance.
/// VI: Query lấy số dư tài khoản billing.
/// </summary>
public record GetBillingAccountBalanceQuery(Guid AccountId) : IRequest<decimal?>;

/// <summary>
/// EN: Handler for GetBillingAccountBalanceQuery.
/// VI: Handler cho GetBillingAccountBalanceQuery.
/// </summary>
public class GetBillingAccountBalanceQueryHandler : IRequestHandler<GetBillingAccountBalanceQuery, decimal?>
{
    private readonly AdsBillingServiceContext _context;

    public GetBillingAccountBalanceQueryHandler(AdsBillingServiceContext context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    public async Task<decimal?> Handle(GetBillingAccountBalanceQuery request, CancellationToken cancellationToken)
    {
        var balance = await _context.BillingAccounts
            .AsNoTracking()
            .Where(a => a.Id == request.AccountId)
            .Select(a => (decimal?)a.Balance)
            .FirstOrDefaultAsync(cancellationToken);

        return balance;
    }
}
