namespace CMSMicroservice.Application.TransactionsCQ.Queries.GetAllTransactionsByFilter;
public class GetAllTransactionsByFilterQueryHandler : IRequestHandler<GetAllTransactionsByFilterQuery, GetAllTransactionsByFilterResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetAllTransactionsByFilterResponseDto> Handle(GetAllTransactionsByFilterQuery request, CancellationToken cancellationToken)
    {
        var query = _context.Transactions
            .ApplyOrder(sortBy: request.SortBy)
            .AsNoTracking()
            .AsQueryable();
        if (request.Filter is not null)
        {
            query = query
                .Where(x => request.Filter.Id == null || x.Id == request.Filter.Id)
                .Where(x => request.Filter.Amount == null || x.Amount == request.Filter.Amount)
                .Where(x => request.Filter.Description == null || x.Description.Contains(request.Filter.Description))
                .Where(x => request.Filter.PaymentStatus == null || x.PaymentStatus== request.Filter.PaymentStatus)
                .Where(x => request.Filter.PaymentDate == null || x.PaymentDate == request.Filter.PaymentDate)
                .Where(x => request.Filter.RefId == null || x.RefId.Contains(request.Filter.RefId))
                .Where(x => request.Filter.Type == null || x.Type == request.Filter.Type)
;
        }
        return new GetAllTransactionsByFilterResponseDto
        {
            MetaData = await query.GetMetaData(request.PaginationState, cancellationToken),
            Models = await query.PaginatedListAsync(paginationState: request.PaginationState)
                .ProjectToType<GetAllTransactionsByFilterResponseModel>().ToListAsync(cancellationToken)
        };        
    }
}
