from api_graphql.abc.mutation_abc import MutationABC
from api_graphql.input.feature_flag_input import FeatureFlagInput
from core.logger import APILogger
from data.schemas.system.feature_flag import FeatureFlag
from data.schemas.system.feature_flag_dao import featureFlagDao
from service.permission.permissions_enum import Permissions

logger = APILogger(__name__)


class FeatureFlagMutation(MutationABC):
    def __init__(self):
        MutationABC.__init__(self, "FeatureFlag")
        self.mutation(
            "change",
            self.resolve_change,
            FeatureFlagInput,
            require_any_permission=[Permissions.administrator],
        )

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

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

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

        return await featureFlagDao.get_by_id(setting.id)
