namespace CMSMicroservice.Application.UserRoleCQ.Queries.GetAllUserRoleByFilter;
public class GetAllUserRoleByFilterQueryHandler : IRequestHandler<GetAllUserRoleByFilterQuery, GetAllUserRoleByFilterResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetAllUserRoleByFilterResponseDto> Handle(GetAllUserRoleByFilterQuery request, CancellationToken cancellationToken)
    {
        var query = _context.UserRoles
            .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.RoleId == null || x.RoleId == request.Filter.RoleId)
                .Where(x => request.Filter.UserId == null || x.UserId == request.Filter.UserId)
;
        }
        return new GetAllUserRoleByFilterResponseDto
        {
            MetaData = await query.GetMetaData(request.PaginationState, cancellationToken),
            Models = await query.PaginatedListAsync(paginationState: request.PaginationState)
                .ProjectToType<GetAllUserRoleByFilterResponseModel>().ToListAsync(cancellationToken)
        };        
    }
}
