namespace CMSMicroservice.Application.RoleCQ.Queries.GetAllRoleByFilter;
public class GetAllRoleByFilterQueryHandler : IRequestHandler<GetAllRoleByFilterQuery, GetAllRoleByFilterResponseDto>
{
    private readonly IApplicationDbContext _context;

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

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