namespace CMSMicroservice.Application.ProductCategoryCQ.Queries.GetAllProductCategoryByFilter;
public class GetAllProductCategoryByFilterQueryHandler : IRequestHandler<GetAllProductCategoryByFilterQuery, GetAllProductCategoryByFilterResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetAllProductCategoryByFilterResponseDto> Handle(GetAllProductCategoryByFilterQuery request, CancellationToken cancellationToken)
    {
        var query = _context.ProductCategories
            .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.CategoryId == null || x.CategoryId==request.Filter.CategoryId)
;
        }
        return new GetAllProductCategoryByFilterResponseDto
        {
            MetaData = await query.GetMetaData(request.PaginationState, cancellationToken),
            Models = await query.PaginatedListAsync(paginationState: request.PaginationState)
                .ProjectToType<GetAllProductCategoryByFilterResponseModel>().ToListAsync(cancellationToken)
        };        
    }
}
