Refactor api and logic