refactor: reduce complexity, and duplicate code