namespace CMSMicroservice.Application.PaymentTransactionCQ.Queries.GetAllPaymentTransactionByFilter;

public class GetAllPaymentTransactionByFilterQueryHandler
    : IRequestHandler<GetAllPaymentTransactionByFilterQuery, GetAllPaymentTransactionByFilterResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetAllPaymentTransactionByFilterResponseDto> Handle(
        GetAllPaymentTransactionByFilterQuery request,
        CancellationToken cancellationToken)
    {
        var query = _context.PaymentTransactions
            .AsNoTracking()
            .ApplyPaymentTransactionFilter(request.Filter)
            .ApplyOrder(sortBy: request.SortBy ?? "-Created");

        return new GetAllPaymentTransactionByFilterResponseDto
        {
            MetaData = await query.GetMetaData(request.PaginationState, cancellationToken),
            Models = await query
                .PaginatedListAsync(paginationState: request.PaginationState)
                .Select(x => new GetAllPaymentTransactionByFilterResponseModel
                {
                    Id = x.Id,
                    UserId = x.UserId,
                    Mobile = x.Mobile,
                    GatewayProvider = x.GatewayProvider,
                    Amount = x.Amount,
                    Authority = x.Authority,
                    PaymentStatus = x.PaymentStatus,
                    VerificationStatusCode = x.VerificationStatusCode,
                    VerificationStatusMessage = x.VerificationStatusMessage,
                    RefId = x.RefId,
                    CardPan = x.CardPan,
                    OrderId = x.OrderId,
                    TransactionId = x.TransactionId,
                    Description = x.Description,
                    Created = x.Created
                })
                .ToListAsync(cancellationToken)
        };
    }
}
