from api.auth.keycloak_client import Keycloak
from api.broadcast import broadcast
from api.route import Route
from api_graphql.abc.mutation_abc import MutationABC
from api_graphql.input.user_create_input import UserCreateInput
from api_graphql.input.user_update_input import UserUpdateInput
from core.logger import APILogger
from data.schemas.administration.user import User
from data.schemas.administration.user_dao import userDao
from data.schemas.permission.role_dao import roleDao
from data.schemas.permission.role_user import RoleUser
from data.schemas.permission.role_user_dao import roleUserDao
from service.permission.permissions_enum import Permissions

logger = APILogger(__name__)


class UserMutation(MutationABC):
    def __init__(self):
        MutationABC.__init__(self, "User")
        self.mutation(
            "create",
            self.resolve_create,
            UserCreateInput,
            require_any_permission=[Permissions.users_create],
        )
        self.mutation(
            "update",
            self.resolve_update,
            UserUpdateInput,
            require_any_permission=[Permissions.users_update],
        )
        self.mutation(
            "delete",
            self.resolve_delete,
            require_any_permission=[Permissions.users_delete],
        )
        self.mutation(
            "restore",
            self.resolve_restore,
            require_any_permission=[Permissions.users_delete],
        )

    @staticmethod
    async def resolve_create(obj: UserCreateInput, *_):
        logger.debug(f"create user: {obj.__dict__}")

        # ensure keycloak knows a user with this keycloak_id
        # get_user should raise an exception if the user does not exist
        kc_user = Keycloak.admin.get_user(obj.keycloak_id)
        if kc_user is None:
            raise ValueError(f"Keycloak user with id {obj.keycloak_id} does not exist")

        user = User(0, obj.keycloak_id)
        user_id = await userDao.create(user)
        user = await userDao.get_by_id(user_id)
        await roleUserDao.create_many([RoleUser(0, user.id, x) for x in set(obj.roles)])

        return user

    async def resolve_update(self, obj: UserUpdateInput, *_):
        logger.debug(f"update user: {obj.__dict__}")
        user = await userDao.get_by_id(obj.id)

        await self._resolve_assignments(
            obj.get("roles", []),
            user,
            RoleUser.user_id,
            RoleUser.role_id,
            userDao,
            roleUserDao,
            RoleUser,
            roleDao,
        )

        return user

    @staticmethod
    async def resolve_delete(*_, id: int):
        logger.debug(f"delete user: {id}")
        user = await userDao.get_by_id(id)
        await userDao.delete(user)
        try:
            active_user = await Route.get_user_or_default()
            if active_user is not None and active_user.id == user.id:
                await broadcast.publish("userLogout", user.id)
                Keycloak.admin.user_logout(user_id=user.keycloak_id)
        except Exception as e:
            logger.error(f"Failed to logout user from Keycloak", e)
        return True

    @staticmethod
    async def resolve_restore(*_, id: int):
        logger.debug(f"restore user: {id}")
        user = await userDao.get_by_id(id)
        await userDao.restore(user)
        return True
