# --------------------------------------------------------------------------------------------
# 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 volume bucket create",
)
class Create(AAZCommand):
    """Create a bucket for a volume. A bucket allows additional services, such as AI services, connect to the volume data contained in those buckets.

    :example: Buckets_CreateOrUpdate
        az netappfiles volume bucket create --resource-group myRG --account-name account1 --pool-name pool1 --volume-name volume1 --bucket-name bucket1 --path /path --group-id 1000 --user-id 1001 --permissions ReadOnly --fqdn fullyqualified.domainname.com --certificate-object <REDACTED> --on-certificate-conflict-action Update
    """

    _aaz_info = {
        "version": "2026-04-01",
        "resources": [
            ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.netapp/netappaccounts/{}/capacitypools/{}/volumes/{}/buckets/{}", "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, self._output)

    _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", "--account-name"],
            help="The name of the NetApp account",
            required=True,
            fmt=AAZStrArgFormat(
                pattern="^[a-zA-Z0-9][a-zA-Z0-9\\-_]{0,127}$",
            ),
        )
        _args_schema.bucket_name = AAZStrArg(
            options=["-n", "--name", "--bucket-name"],
            help="The name of the bucket",
            required=True,
            fmt=AAZStrArgFormat(
                pattern="^([a-z]|(\\d(?!\\d{0,2}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})))([a-z\\d]|(\\.(?!(\\.|-)))|(-(?!\\.))){1,61}[a-z\\d]$",
                max_length=63,
                min_length=3,
            ),
        )
        _args_schema.pool_name = AAZStrArg(
            options=["-p", "--pool-name"],
            help="The name of the capacity pool",
            required=True,
            fmt=AAZStrArgFormat(
                pattern="^[a-zA-Z0-9][a-zA-Z0-9\\-_]{0,63}$",
                max_length=64,
                min_length=1,
            ),
        )
        _args_schema.resource_group = AAZResourceGroupNameArg(
            required=True,
        )
        _args_schema.volume_name = AAZStrArg(
            options=["-v", "--volume-name"],
            help="The name of the volume",
            required=True,
            fmt=AAZStrArgFormat(
                pattern="^[a-zA-Z][a-zA-Z0-9\\-_]{0,63}$",
                max_length=64,
                min_length=1,
            ),
        )

        # define Arg Group "CertificateAkvDetails"

        _args_schema = cls._args_schema
        _args_schema.certificate_key_vault_uri = AAZStrArg(
            options=["--cert-kv-uri", "--certificate-key-vault-uri"],
            arg_group="CertificateAkvDetails",
            help="The base URI of the Azure Key Vault that is used when retrieving the bucket certificate.",
        )
        _args_schema.certificate_name = AAZStrArg(
            options=["--certificate-name"],
            arg_group="CertificateAkvDetails",
            help="The name of the bucket server certificate stored in the Azure Key Vault.",
            fmt=AAZStrArgFormat(
                pattern="^[a-zA-Z0-9-]{1,127}$",
                max_length=127,
                min_length=1,
            ),
        )

        # define Arg Group "CifsUser"

        _args_schema = cls._args_schema
        _args_schema.username = AAZStrArg(
            options=["--username"],
            arg_group="CifsUser",
            help="The CIFS user's username",
        )

        # define Arg Group "CredentialsAkvDetails"

        _args_schema = cls._args_schema
        _args_schema.credentials_key_vault_uri = AAZStrArg(
            options=["--creds-kv-uri", "--credentials-key-vault-uri"],
            arg_group="CredentialsAkvDetails",
            help="The base URI of the Azure Key Vault that is used when storing the bucket credentials.",
        )
        _args_schema.secret_name = AAZStrArg(
            options=["--secret-name"],
            arg_group="CredentialsAkvDetails",
            help="The name of the secret stored in Azure Key Vault. The associated key pair has the following structure:  { \"access_key_id\": `\"<REDACTED>\"`, \"secret_access_key\": `\"<REDACTED>\"` }",
            fmt=AAZStrArgFormat(
                pattern="^[a-zA-Z0-9-]{1,127}$",
                max_length=127,
                min_length=1,
            ),
        )

        # define Arg Group "NfsUser"

        _args_schema = cls._args_schema
        _args_schema.group_id = AAZIntArg(
            options=["--group-id"],
            arg_group="NfsUser",
            help="The NFS user's GID",
        )
        _args_schema.user_id = AAZIntArg(
            options=["--user-id"],
            arg_group="NfsUser",
            help="The NFS user's UID",
        )

        # define Arg Group "Properties"

        _args_schema = cls._args_schema
        _args_schema.path = AAZStrArg(
            options=["--path"],
            arg_group="Properties",
            help="The volume path mounted inside the bucket. The default is the root path '/' if no value is provided when the bucket is created.",
            default="/",
        )
        _args_schema.permissions = AAZStrArg(
            options=["--permissions"],
            arg_group="Properties",
            help="Access permissions for the bucket. Either ReadOnly or ReadWrite. The default is ReadOnly if no value is provided during bucket creation.",
            default="ReadOnly",
            enum={"ReadOnly": "ReadOnly", "ReadWrite": "ReadWrite"},
        )

        # define Arg Group "Server"

        _args_schema = cls._args_schema
        _args_schema.certificate_object = AAZPasswordArg(
            options=["--certificate-object"],
            arg_group="Server",
            help="The base64-encoded contents of a PEM file, which includes both the bucket server's certificate and private key. It is generated by the end user and allows the user to access volume data in a read-only manner. Note: This is only used when Azure Key Vault is not configured. This property is mutually exclusive with the Azure Key Vault 'akv' properties.",
            fmt=AAZStrArgFormat(
                max_length=20480,
                min_length=1,
            ),
            blank=AAZPromptPasswordInput(
                msg="Password:",
            ),
        )
        _args_schema.fqdn = AAZStrArg(
            options=["--fqdn"],
            arg_group="Server",
            help="The host part of the bucket URL, resolving to the bucket IP address and allowed by the server certificate.",
        )
        _args_schema.on_certificate_conflict_action = AAZStrArg(
            options=["--cert-conflict-action", "--on-certificate-conflict-action"],
            arg_group="Server",
            help="Action to take when there is a certificate conflict. Possible values include: 'Update', 'Fail'",
            enum={"Fail": "Fail", "Update": "Update"},
        )
        return cls._args_schema

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

    @register_callback
    def pre_operations(self):
        pass

    @register_callback
    def post_operations(self):
        pass

    def _output(self, *args, **kwargs):
        result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True)
        return result

    class BucketsCreateOrUpdate(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,
                    self.on_200_201,
                    self.on_error,
                    lro_options={"final-state-via": "azure-async-operation"},
                    path_format_arguments=self.url_parameters,
                )
            if session.http_response.status_code in [200, 201]:
                return self.client.build_lro_polling(
                    self.ctx.args.no_wait,
                    session,
                    self.on_200_201,
                    self.on_error,
                    lro_options={"final-state-via": "azure-async-operation"},
                    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}/capacityPools/{poolName}/volumes/{volumeName}/buckets/{bucketName}",
                **self.url_parameters
            )

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

        @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(
                    "bucketName", self.ctx.args.bucket_name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "poolName", self.ctx.args.pool_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,
                ),
                **self.serialize_url_param(
                    "volumeName", self.ctx.args.volume_name,
                    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",
                ),
                **self.serialize_header_param(
                    "Accept", "application/json",
                ),
            }
            return parameters

        @property
        def content(self):
            _content_value, _builder = self.new_content_builder(
                self.ctx.args,
                typ=AAZObjectType,
                typ_kwargs={"flags": {"required": True, "client_flatten": True}}
            )
            _builder.set_prop("properties", AAZObjectType, typ_kwargs={"flags": {"client_flatten": True}})

            properties = _builder.get(".properties")
            if properties is not None:
                properties.set_prop("akvDetails", AAZObjectType)
                properties.set_prop("fileSystemUser", AAZObjectType)
                properties.set_prop("path", AAZStrType, ".path")
                properties.set_prop("permissions", AAZStrType, ".permissions")
                properties.set_prop("server", AAZObjectType)

            akv_details = _builder.get(".properties.akvDetails")
            if akv_details is not None:
                akv_details.set_prop("certificateAkvDetails", AAZObjectType)
                akv_details.set_prop("credentialsAkvDetails", AAZObjectType)

            certificate_akv_details = _builder.get(".properties.akvDetails.certificateAkvDetails")
            if certificate_akv_details is not None:
                certificate_akv_details.set_prop("certificateKeyVaultUri", AAZStrType, ".certificate_key_vault_uri")
                certificate_akv_details.set_prop("certificateName", AAZStrType, ".certificate_name")

            credentials_akv_details = _builder.get(".properties.akvDetails.credentialsAkvDetails")
            if credentials_akv_details is not None:
                credentials_akv_details.set_prop("credentialsKeyVaultUri", AAZStrType, ".credentials_key_vault_uri")
                credentials_akv_details.set_prop("secretName", AAZStrType, ".secret_name")

            file_system_user = _builder.get(".properties.fileSystemUser")
            if file_system_user is not None:
                file_system_user.set_prop("cifsUser", AAZObjectType)
                file_system_user.set_prop("nfsUser", AAZObjectType)

            cifs_user = _builder.get(".properties.fileSystemUser.cifsUser")
            if cifs_user is not None:
                cifs_user.set_prop("username", AAZStrType, ".username")

            nfs_user = _builder.get(".properties.fileSystemUser.nfsUser")
            if nfs_user is not None:
                nfs_user.set_prop("groupId", AAZIntType, ".group_id")
                nfs_user.set_prop("userId", AAZIntType, ".user_id")

            server = _builder.get(".properties.server")
            if server is not None:
                server.set_prop("certificateObject", AAZStrType, ".certificate_object", typ_kwargs={"flags": {"secret": True}})
                server.set_prop("fqdn", AAZStrType, ".fqdn")
                server.set_prop("onCertificateConflictAction", AAZStrType, ".on_certificate_conflict_action")

            return self.serialize_content(_content_value)

        def on_200_201(self, session):
            data = self.deserialize_http_content(session)
            self.ctx.set_var(
                "instance",
                data,
                schema_builder=self._build_schema_on_200_201
            )

        _schema_on_200_201 = None

        @classmethod
        def _build_schema_on_200_201(cls):
            if cls._schema_on_200_201 is not None:
                return cls._schema_on_200_201

            cls._schema_on_200_201 = AAZObjectType()

            _schema_on_200_201 = cls._schema_on_200_201
            _schema_on_200_201.id = AAZStrType(
                flags={"read_only": True},
            )
            _schema_on_200_201.name = AAZStrType(
                flags={"read_only": True},
            )
            _schema_on_200_201.properties = AAZObjectType(
                flags={"client_flatten": True},
            )
            _schema_on_200_201.system_data = AAZObjectType(
                serialized_name="systemData",
                flags={"read_only": True},
            )
            _schema_on_200_201.type = AAZStrType(
                flags={"read_only": True},
            )

            properties = cls._schema_on_200_201.properties
            properties.akv_details = AAZObjectType(
                serialized_name="akvDetails",
            )
            properties.file_system_user = AAZObjectType(
                serialized_name="fileSystemUser",
            )
            properties.path = AAZStrType()
            properties.permissions = AAZStrType()
            properties.provisioning_state = AAZStrType(
                serialized_name="provisioningState",
                flags={"read_only": True},
            )
            properties.server = AAZObjectType()
            properties.status = AAZStrType(
                flags={"read_only": True},
            )

            akv_details = cls._schema_on_200_201.properties.akv_details
            akv_details.certificate_akv_details = AAZObjectType(
                serialized_name="certificateAkvDetails",
            )
            akv_details.credentials_akv_details = AAZObjectType(
                serialized_name="credentialsAkvDetails",
            )

            certificate_akv_details = cls._schema_on_200_201.properties.akv_details.certificate_akv_details
            certificate_akv_details.certificate_key_vault_uri = AAZStrType(
                serialized_name="certificateKeyVaultUri",
            )
            certificate_akv_details.certificate_name = AAZStrType(
                serialized_name="certificateName",
            )

            credentials_akv_details = cls._schema_on_200_201.properties.akv_details.credentials_akv_details
            credentials_akv_details.credentials_key_vault_uri = AAZStrType(
                serialized_name="credentialsKeyVaultUri",
            )
            credentials_akv_details.secret_name = AAZStrType(
                serialized_name="secretName",
            )

            file_system_user = cls._schema_on_200_201.properties.file_system_user
            file_system_user.cifs_user = AAZObjectType(
                serialized_name="cifsUser",
            )
            file_system_user.nfs_user = AAZObjectType(
                serialized_name="nfsUser",
            )

            cifs_user = cls._schema_on_200_201.properties.file_system_user.cifs_user
            cifs_user.username = AAZStrType()

            nfs_user = cls._schema_on_200_201.properties.file_system_user.nfs_user
            nfs_user.group_id = AAZIntType(
                serialized_name="groupId",
            )
            nfs_user.user_id = AAZIntType(
                serialized_name="userId",
            )

            server = cls._schema_on_200_201.properties.server
            server.certificate_common_name = AAZStrType(
                serialized_name="certificateCommonName",
                flags={"read_only": True},
            )
            server.certificate_expiry_date = AAZStrType(
                serialized_name="certificateExpiryDate",
                flags={"read_only": True},
            )
            server.fqdn = AAZStrType()
            server.ip_address = AAZStrType(
                serialized_name="ipAddress",
                flags={"read_only": True},
            )
            server.on_certificate_conflict_action = AAZStrType(
                serialized_name="onCertificateConflictAction",
            )

            system_data = cls._schema_on_200_201.system_data
            system_data.created_at = AAZStrType(
                serialized_name="createdAt",
            )
            system_data.created_by = AAZStrType(
                serialized_name="createdBy",
            )
            system_data.created_by_type = AAZStrType(
                serialized_name="createdByType",
            )
            system_data.last_modified_at = AAZStrType(
                serialized_name="lastModifiedAt",
            )
            system_data.last_modified_by = AAZStrType(
                serialized_name="lastModifiedBy",
            )
            system_data.last_modified_by_type = AAZStrType(
                serialized_name="lastModifiedByType",
            )

            return cls._schema_on_200_201


class _CreateHelper:
    """Helper class for Create"""


__all__ = ["Create"]
