refactor messages handling