namespace CMSMicroservice.Application.FactorDetailsCQ.Queries.GetAllFactorDetailsByFilter;
public class GetAllFactorDetailsByFilterQueryHandler : IRequestHandler<GetAllFactorDetailsByFilterQuery, GetAllFactorDetailsByFilterResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetAllFactorDetailsByFilterResponseDto> Handle(GetAllFactorDetailsByFilterQuery request, CancellationToken cancellationToken)
    {
        var query = _context.FactorDetails
            .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.ProductId == null || x.ProductId == request.Filter.ProductId)
                .Where(x => request.Filter.Count == null || x.Count == request.Filter.Count)
                .Where(x => request.Filter.UnitPrice == null || x.UnitPrice == request.Filter.UnitPrice)
                .Where(x => request.Filter.UnitDiscount == null || x.UnitDiscount == request.Filter.UnitDiscount)
                .Where(x => request.Filter.OrderId == null || x.OrderId == request.Filter.OrderId)
                .Where(x => request.Filter.UnitDiscountPrice == null || x.UnitDiscountPrice == request.Filter.UnitDiscountPrice)
                .Where(x => request.Filter.IsChangePrice == null || x.IsChangePrice == request.Filter.IsChangePrice)
;
        }
        return new GetAllFactorDetailsByFilterResponseDto
        {
            MetaData = await query.GetMetaData(request.PaginationState, cancellationToken),
            Models = await query.PaginatedListAsync(paginationState: request.PaginationState)
                .ProjectToType<GetAllFactorDetailsByFilterResponseModel>().ToListAsync(cancellationToken)
        };        
    }
}
