using AdsBillingService.API.Application.DTOs;
using AdsBillingService.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace AdsBillingService.API.Application.Queries;

/// <summary>
/// EN: Query to get billing account by ID.
/// VI: Query lấy thông tin tài khoản billing theo ID.
/// </summary>
public record GetBillingAccountQuery(Guid AccountId) : IRequest<BillingAccountDto?>;

/// <summary>
/// EN: Handler for GetBillingAccountQuery.
/// VI: Handler cho GetBillingAccountQuery.
/// </summary>
public class GetBillingAccountQueryHandler : IRequestHandler<GetBillingAccountQuery, BillingAccountDto?>
{
    private readonly AdsBillingServiceContext _context;

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

    public async Task<BillingAccountDto?> Handle(GetBillingAccountQuery request, CancellationToken cancellationToken)
    {
        var account = await _context.BillingAccounts
            .AsNoTracking()
            .Where(a => a.Id == request.AccountId)
            .Select(a => new BillingAccountDto
            {
                Id = a.Id,
                AdvertiserId = a.AdvertiserId,
                WalletId = a.WalletId,
                PaymentMethod = a.PaymentMethod.ToString(),
                Status = a.Status.ToString(),
                Balance = a.Balance,
                CreditLimit = a.CreditLimit,
                Threshold = a.Threshold != null ? new BillingThresholdDto
                {
                    Amount = a.Threshold.Amount,
                    AutoCharge = a.Threshold.AutoCharge
                } : null,
                CreatedAt = a.CreatedAt,
                UpdatedAt = a.UpdatedAt
            })
            .FirstOrDefaultAsync(cancellationToken);

        return account;
    }
}
