from flask import current_app
from app.repositories import UserRepository
from app.schemas import RegisterSchema
from app.mapper import UserMapper
from app.exception import AlreadyExistException
from werkzeug.security import generate_password_hash


class UserService:
    def __init__(self, user_repository: UserRepository):
        self.user_repository = user_repository

    def get_all_users(self):
        return self.user_repository.get_all_users()

    def register_user(self, user_data: RegisterSchema):
        existData = self.user_repository.get_user_by_email(user_data.email)
        if existData:
            raise AlreadyExistException(entity="Email")

        encrypted_password = generate_password_hash(user_data.password)
        user_data.password = encrypted_password

        data = UserMapper.from_register(user_data)
        return self.user_repository.insert_user(data)
