from clarabot_nano_common.common.handler.error import NanoHandlerError
from clarabot_nano_common.common.protocol.errors import NANO_REQUEST_ERROR_ADMIN_SESSION
from clarabot_nano_common.common.protocol.request import NanoRequestContext

from clarabot_nano.common.request.server_general import AdminChangePasswordRequest
from clarabot_nano.server.general.handler.admin.config_update.base import AbstractAdminConfigUpdateServerHandler


class ChangeAdminPasswordHandler(AbstractAdminConfigUpdateServerHandler):
    REQUIRES_ADMIN_SESSION = False  # custom handling if it is not set yet

    HANDLER_KEY = AdminChangePasswordRequest.TYPE_KEY

    def _create_config_update_request(self) -> dict:
        if self.context[NanoRequestContext.ADMIN_CAN_SETUP_PW] is True:
            pass  # allow initial password setup
        elif self.context[NanoRequestContext.ADMIN_SESSION_TTL] is None:
            raise NanoHandlerError(NANO_REQUEST_ERROR_ADMIN_SESSION, "Admin session missing", self)
        return {
            "_handler_key": "admin_password",
            "admin_password": self.payload.get(AdminChangePasswordRequest.NEW_PASSWORD),
        }

    def _log_message(self) -> str:
        return "Admin password changed"
