using CMSMicroservice.Application.PaymentTransactionCQ.Queries.GetAllPaymentTransactionByFilter;

namespace CMSMicroservice.Application.PaymentTransactionCQ.Queries.GetPaymentTransactionSummary;

public class GetPaymentTransactionSummaryQueryHandler
    : IRequestHandler<GetPaymentTransactionSummaryQuery, GetPaymentTransactionSummaryResponseDto>
{
    private readonly IApplicationDbContext _context;

    public GetPaymentTransactionSummaryQueryHandler(IApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<GetPaymentTransactionSummaryResponseDto> Handle(
        GetPaymentTransactionSummaryQuery request,
        CancellationToken cancellationToken)
    {
        var query = _context.PaymentTransactions
            .AsNoTracking()
            .ApplyPaymentTransactionFilter(request.Filter);

        var totalCount = await query.LongCountAsync(cancellationToken);
        var totalAmount = totalCount > 0 ? await query.SumAsync(x => x.Amount, cancellationToken) : 0;
        var successfulCount = await query.LongCountAsync(x => x.PaymentStatus, cancellationToken);
        var pendingCount = await query.LongCountAsync(x => !x.PaymentStatus, cancellationToken);

        return new GetPaymentTransactionSummaryResponseDto
        {
            TotalCount = totalCount,
            TotalAmount = totalAmount,
            SuccessfulCount = successfulCount,
            PendingCount = pendingCount
        };
    }
}
