namespace CMSMicroservice.Application.ProductGalleriesCQ.Queries.GetAllProductGalleriesByFilter;
public class GetAllProductGallerysByFilterQueryHandler : IRequestHandler<GetAllProductGalleriesByFilterQuery, GetAllProductGallerysByFilterResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetAllProductGallerysByFilterResponseDto> Handle(GetAllProductGalleriesByFilterQuery request, CancellationToken cancellationToken)
    {
        var query = _context.ProductGalleries
            .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.ProductImageId == null || x.ProductImageId == request.Filter.ProductImageId)
                .Where(x => request.Filter.ProductId == null || x.ProductId == request.Filter.ProductId)
;
        }
        return new GetAllProductGallerysByFilterResponseDto
        {
            MetaData = await query.GetMetaData(request.PaginationState, cancellationToken),
            Models = await query.PaginatedListAsync(paginationState: request.PaginationState)
                .ProjectToType<GetAllProductGallerysByFilterResponseModel>().ToListAsync(cancellationToken)
        };        
    }
}
