using CMSMicroservice.Application.TransactionsCQ.Queries.GetAllTransactionsByFilter;
using CMSMicroservice.Domain.Enums;

namespace CMSMicroservice.Application.TransactionsCQ.Queries.GetTransactionSummary;

public class GetTransactionSummaryQueryHandler
    : IRequestHandler<GetTransactionSummaryQuery, GetTransactionSummaryResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetTransactionSummaryResponseDto> Handle(
        GetTransactionSummaryQuery request,
        CancellationToken cancellationToken)
    {
        var query = _context.Transactions
            .AsNoTracking()
            .ApplyTransactionFilter(request.Filter);

        var totalCount = await query.LongCountAsync(cancellationToken);
        var totalAmount = totalCount > 0 ? await query.SumAsync(x => x.Amount, cancellationToken) : 0;
        var successCount = await query.LongCountAsync(x => x.PaymentStatus == PaymentStatus.Success, cancellationToken);
        var pendingCount = await query.LongCountAsync(x => x.PaymentStatus == PaymentStatus.Pending, cancellationToken);
        var rejectCount = await query.LongCountAsync(x => x.PaymentStatus == PaymentStatus.Reject, cancellationToken);

        return new GetTransactionSummaryResponseDto
        {
            TotalCount = totalCount,
            TotalAmount = totalAmount,
            SuccessCount = successCount,
            PendingCount = pendingCount,
            RejectCount = rejectCount
        };
    }
}
