namespace CMSMicroservice.Application.UserWalletHistoryCQ.Queries.GetAllUserWalletHistoryByFilter;
public class GetAllUserWalletHistoryByFilterQueryHandler : IRequestHandler<GetAllUserWalletHistoryByFilterQuery, GetAllUserWalletHistoryByFilterResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetAllUserWalletHistoryByFilterResponseDto> Handle(GetAllUserWalletHistoryByFilterQuery request, CancellationToken cancellationToken)
    {
        var query = _context.UserWalletHistories
            .Include(i=>i.Wallet)
            .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.WalletId == null || x.WalletId == request.Filter.WalletId)
                .Where(x => request.Filter.CurrentBalance == null || x.CurrentBalance == request.Filter.CurrentBalance)
                .Where(x => request.Filter.ChangeValue == null || x.ChangeValue == request.Filter.ChangeValue)
                .Where(x => request.Filter.IsIncrease == null || x.IsIncrease == request.Filter.IsIncrease)
                .Where(x => request.Filter.RefrenceId == null || x.RefrenceId == request.Filter.RefrenceId)
                .Where(x => request.Filter.UserId == null || x.Wallet.UserId == request.Filter.UserId)
;
        }
        return new GetAllUserWalletHistoryByFilterResponseDto
        {
            MetaData = await query.GetMetaData(request.PaginationState, cancellationToken),
            Models = await query.PaginatedListAsync(paginationState: request.PaginationState)
                .ProjectToType<GetAllUserWalletHistoryByFilterResponseModel>().ToListAsync(cancellationToken)
        };        
    }
}
