# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
#
# Code generated by aaz-dev-tools
# --------------------------------------------------------------------------------------------

# pylint: skip-file
# flake8: noqa

from azure.cli.core.aaz import *


@register_command(
    "netappfiles account change-key-vault",
    confirmation="Are you sure you want to perform this operation?",
)
class ChangeKeyVault(AAZCommand):
    """Change KeyVault/Managed HSM that is used for encryption of volumes under NetApp account

    Affects existing volumes that are encrypted with Key Vault/Managed HSM, and new volumes. Supports HSM to Key Vault, Key Vault to HSM, HSM to HSM and Key Vault to Key Vault.

    :example: Accounts_ChangeKeyVault
        az netappfiles account change-key-vault --resource-group myRG --account-name account1 --key-vault-uri https://my-key-vault.managedhsm.azure.net --key-name rsakey --key-vault-resource-id /subscriptions/D633CC2E-722B-4AE1-B636-BBD9E4C60ED9/resourceGroups/myRG/providers/Microsoft.KeyVault/managedHSMs/my-hsm --key-vault-private-endpoints "[{virtual-network-id:/subscriptions/D633CC2E-722B-4AE1-B636-BBD9E4C60ED9/resourceGroups/myRG/providers/Microsoft.Network/virtualNetworks/vnet1,private-endpoint-id:/subscriptions/D633CC2E-722B-4AE1-B636-BBD9E4C60ED9/resourceGroups/myRG/providers/Microsoft.Network/privateEndpoints/privip1}]"
    """

    _aaz_info = {
        "version": "2026-04-01",
        "resources": [
            ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.netapp/netappaccounts/{}/changekeyvault", "2026-04-01"],
        ]
    }

    AZ_SUPPORT_NO_WAIT = True

    def _handler(self, command_args):
        super()._handler(command_args)
        return self.build_lro_poller(self._execute_operations, None)

    _args_schema = None

    @classmethod
    def _build_arguments_schema(cls, *args, **kwargs):
        if cls._args_schema is not None:
            return cls._args_schema
        cls._args_schema = super()._build_arguments_schema(*args, **kwargs)

        # define Arg Group ""

        _args_schema = cls._args_schema
        _args_schema.account_name = AAZStrArg(
            options=["-a", "-n", "--account-name"],
            help="The name of the NetApp account",
            required=True,
            id_part="name",
            fmt=AAZStrArgFormat(
                pattern="^[a-zA-Z0-9][a-zA-Z0-9\\-_]{0,127}$",
            ),
        )
        _args_schema.resource_group = AAZResourceGroupNameArg(
            required=True,
        )

        # define Arg Group "Body"

        _args_schema = cls._args_schema
        _args_schema.key_name = AAZStrArg(
            options=["--key-name"],
            arg_group="Body",
            help="The name of the key that should be used for encryption.",
        )
        _args_schema.key_vault_private_endpoints = AAZListArg(
            options=["--endpoint-pairs", "--key-vault-private-endpoints"],
            arg_group="Body",
            help="Pairs of virtual network ID and private endpoint ID. Every virtual network that has volumes encrypted with customer-managed keys needs its own key vault private endpoint.",
        )
        _args_schema.key_vault_resource_id = AAZResourceIdArg(
            options=["--keyvault-resource-id", "--key-vault-resource-id"],
            arg_group="Body",
            help="Azure resource ID of the key vault/managed HSM that should be used for encryption.",
        )
        _args_schema.key_vault_uri = AAZStrArg(
            options=["-v", "--key-vault-uri"],
            arg_group="Body",
            help="The URI of the key vault/managed HSM that should be used for encryption.",
        )

        key_vault_private_endpoints = cls._args_schema.key_vault_private_endpoints
        key_vault_private_endpoints.Element = AAZObjectArg()

        _element = cls._args_schema.key_vault_private_endpoints.Element
        _element.private_endpoint_id = AAZResourceIdArg(
            options=["private-endpoint-id"],
            help="Identifier of the private endpoint to reach the Azure Key Vault",
        )
        _element.virtual_network_id = AAZResourceIdArg(
            options=["virtual-network-id"],
            help="Identifier for the virtual network id",
        )
        return cls._args_schema

    def _execute_operations(self):
        self.pre_operations()
        yield self.AccountsChangeKeyVault(ctx=self.ctx)()
        self.post_operations()

    @register_callback
    def pre_operations(self):
        pass

    @register_callback
    def post_operations(self):
        pass

    class AccountsChangeKeyVault(AAZHttpOperation):
        CLIENT_TYPE = "MgmtClient"

        def __call__(self, *args, **kwargs):
            request = self.make_request()
            session = self.client.send_request(request=request, stream=False, **kwargs)
            if session.http_response.status_code in [202]:
                return self.client.build_lro_polling(
                    self.ctx.args.no_wait,
                    session,
                    None,
                    self.on_error,
                    lro_options={"final-state-via": "location"},
                    path_format_arguments=self.url_parameters,
                )

            return self.on_error(session.http_response)

        @property
        def url(self):
            return self.client.format_url(
                "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/changeKeyVault",
                **self.url_parameters
            )

        @property
        def method(self):
            return "POST"

        @property
        def error_format(self):
            return "MgmtErrorFormat"

        @property
        def url_parameters(self):
            parameters = {
                **self.serialize_url_param(
                    "accountName", self.ctx.args.account_name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "resourceGroupName", self.ctx.args.resource_group,
                    required=True,
                ),
                **self.serialize_url_param(
                    "subscriptionId", self.ctx.subscription_id,
                    required=True,
                ),
            }
            return parameters

        @property
        def query_parameters(self):
            parameters = {
                **self.serialize_query_param(
                    "api-version", "2026-04-01",
                    required=True,
                ),
            }
            return parameters

        @property
        def header_parameters(self):
            parameters = {
                **self.serialize_header_param(
                    "Content-Type", "application/json",
                ),
            }
            return parameters

        @property
        def content(self):
            _content_value, _builder = self.new_content_builder(
                self.ctx.args,
                typ=AAZObjectType,
                typ_kwargs={"flags": {"client_flatten": True}}
            )
            _builder.set_prop("keyName", AAZStrType, ".key_name", typ_kwargs={"flags": {"required": True}})
            _builder.set_prop("keyVaultPrivateEndpoints", AAZListType, ".key_vault_private_endpoints", typ_kwargs={"flags": {"required": True}})
            _builder.set_prop("keyVaultResourceId", AAZStrType, ".key_vault_resource_id")
            _builder.set_prop("keyVaultUri", AAZStrType, ".key_vault_uri", typ_kwargs={"flags": {"required": True}})

            key_vault_private_endpoints = _builder.get(".keyVaultPrivateEndpoints")
            if key_vault_private_endpoints is not None:
                key_vault_private_endpoints.set_elements(AAZObjectType, ".")

            _elements = _builder.get(".keyVaultPrivateEndpoints[]")
            if _elements is not None:
                _elements.set_prop("privateEndpointId", AAZStrType, ".private_endpoint_id")
                _elements.set_prop("virtualNetworkId", AAZStrType, ".virtual_network_id")

            return self.serialize_content(_content_value)


class _ChangeKeyVaultHelper:
    """Helper class for ChangeKeyVault"""


__all__ = ["ChangeKeyVault"]
