from clarabot_nano.common.handler.base import NanoHandlerError
from clarabot_nano.common.protocol.errors import NANO_REQUEST_ERROR_ADMIN_PASSWORD
from clarabot_nano.common.protocol.request import NanoBaseRequest
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_PASSWORD = False  # custom handling if it is not set yet

    HANDLER_KEY = AdminChangePasswordRequest.TYPE_KEY

    def _create_config_update_request(self) -> dict:
        if self.extracted_config.can_setup_password():
            pass  # allow initial password setup
        elif not self.extracted_config.check_admin_password(self.payload.get(NanoBaseRequest.ADMIN_PASSWORD)):
            raise NanoHandlerError(
                NANO_REQUEST_ERROR_ADMIN_PASSWORD, "Current admin-password required for changing it", self.context
            )
        return {
            "_handler_key": "admin_password",
            "admin_password": self.payload.get(AdminChangePasswordRequest.NEW_PASSWORD),
        }

    def _log_message(self) -> str:
        return "Nano admin password updated"
