namespace CMSMicroservice.Application.ProductImagesCQ.Queries.GetAllProductImagesByFilter;
public class GetAllProductImagesByFilterQueryHandler : IRequestHandler<GetAllProductImagesByFilterQuery, GetAllProductImagesByFilterResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetAllProductImagesByFilterResponseDto> Handle(GetAllProductImagesByFilterQuery request, CancellationToken cancellationToken)
    {
        var query = _context.ProductImages
            .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.Title == null || x.Title.Contains(request.Filter.Title))
                .Where(x => request.Filter.ImagePath == null || x.ImagePath.Contains(request.Filter.ImagePath))
                .Where(x => request.Filter.ImageThumbnailPath == null || x.ImageThumbnailPath.Contains(request.Filter.ImageThumbnailPath))
;
        }
        return new GetAllProductImagesByFilterResponseDto
        {
            MetaData = await query.GetMetaData(request.PaginationState, cancellationToken),
            Models = await query.PaginatedListAsync(paginationState: request.PaginationState)
                .ProjectToType<GetAllProductImagesByFilterResponseModel>().ToListAsync(cancellationToken)
        };        
    }
}
