namespace CMSMicroservice.Application.ProductTagCQ.Queries.GetAllProductTagByFilter;
public class GetAllProductTagByFilterQueryHandler : IRequestHandler<GetAllProductTagByFilterQuery, GetAllProductTagByFilterResponseDto>
{
    private readonly IApplicationDbContext _context;

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

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

