from api_graphql.abc.mutation_abc import MutationABC
from api_graphql.input.api_key_create_input import ApiKeyCreateInput
from api_graphql.input.api_key_update_input import ApiKeyUpdateInput
from core.logger import APILogger
from data.schemas.administration.api_key import ApiKey
from data.schemas.administration.api_key_dao import apiKeyDao
from data.schemas.permission.api_key_permission import ApiKeyPermission
from data.schemas.permission.api_key_permission_dao import apiKeyPermissionDao
from data.schemas.permission.permission_dao import permissionDao
from service.permission.permissions_enum import Permissions

logger = APILogger(__name__)


class APIKeyMutation(MutationABC):
    def __init__(self):
        MutationABC.__init__(self, "ApiKey")

        self.mutation(
            "create",
            self.resolve_create,
            ApiKeyCreateInput,
            require_any_permission=[Permissions.api_keys_create],
        )
        self.mutation(
            "update",
            self.resolve_update,
            ApiKeyUpdateInput,
            require_any_permission=[Permissions.api_keys_update],
        )
        self.mutation(
            "delete",
            self.resolve_delete,
            require_any_permission=[Permissions.api_keys_delete],
        )
        self.mutation(
            "restore",
            self.resolve_restore,
            require_any_permission=[Permissions.api_keys_delete],
        )

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

        api_key = ApiKey.new(obj.identifier)
        await apiKeyDao.create(api_key)
        api_key = await apiKeyDao.get_single_by([{ApiKey.identifier: obj.identifier}])
        await apiKeyPermissionDao.create_many(
            [ApiKeyPermission(0, api_key.id, x) for x in obj.permissions]
        )
        return api_key

    async def resolve_update(self, obj: ApiKeyUpdateInput, *_):
        logger.debug(f"update api key: {input}")
        api_key = await apiKeyDao.get_by_id(obj.id)

        await self._resolve_assignments(
            obj.get("permissions", []),
            api_key,
            ApiKeyPermission.api_key_id,
            ApiKeyPermission.permission_id,
            apiKeyDao,
            apiKeyPermissionDao,
            ApiKeyPermission,
            permissionDao,
        )

        return api_key

    @staticmethod
    async def resolve_delete(*_, id: str):
        logger.debug(f"delete api key: {id}")
        api_key = await apiKeyDao.get_by_id(id)
        await apiKeyDao.delete(api_key)
        return True

    @staticmethod
    async def resolve_restore(*_, id: str):
        logger.debug(f"restore api key: {id}")
        api_key = await apiKeyDao.get_by_id(id)
        await apiKeyDao.restore(api_key)
        return True
