from api_graphql.abc.mutation_abc import MutationABC
from api_graphql.input.setting_input import SettingInput
from core.logger import APILogger
from data.schemas.system.setting import Setting
from data.schemas.system.setting_dao import settingDao
from service.permission.permissions_enum import Permissions

logger = APILogger(__name__)


class SettingMutation(MutationABC):
    def __init__(self):
        MutationABC.__init__(self, "Setting")
        self.mutation(
            "change",
            self.resolve_change,
            SettingInput,
            require_any_permission=[Permissions.settings_update],
        )

    @staticmethod
    async def resolve_change(obj: SettingInput, *_):
        logger.debug(f"create new setting: {input}")

        setting = await settingDao.find_single_by({Setting.key: obj.key})
        if setting is None:
            raise ValueError(f"Setting with key {obj.key} not found")

        setting.value = obj.value
        await settingDao.update(setting)

        return await settingDao.get_by_id(setting.id)
