# pylint: disable=too-many-lines
# coding=utf-8
# --------------------------------------------------------------------------
# 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 Microsoft (R) Python Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from collections.abc import MutableMapping
import datetime
from io import IOBase
import json
from typing import Any, AsyncIterator, Callable, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse

from azure.core import AsyncPipelineClient
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
    ClientAuthenticationError,
    HttpResponseError,
    ResourceExistsError,
    ResourceNotFoundError,
    ResourceNotModifiedError,
    StreamClosedError,
    StreamConsumedError,
    map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import AsyncHttpResponse, HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling

from ... import models as _models
from ..._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize
from ..._utils.serialization import Deserializer, Serializer
from ...operations._operations import (
    build_address_validate_request,
    build_agreements_get_request,
    build_agreements_list_by_billing_account_request,
    build_associated_tenants_create_or_update_request,
    build_associated_tenants_delete_request,
    build_associated_tenants_get_request,
    build_associated_tenants_list_by_billing_account_request,
    build_available_balances_get_by_billing_account_request,
    build_available_balances_get_by_billing_profile_request,
    build_billing_accounts_add_payment_terms_request,
    build_billing_accounts_cancel_payment_terms_request,
    build_billing_accounts_confirm_transition_request,
    build_billing_accounts_get_request,
    build_billing_accounts_list_invoice_sections_by_create_subscription_permission_request,
    build_billing_accounts_list_request,
    build_billing_accounts_update_request,
    build_billing_accounts_validate_payment_terms_request,
    build_billing_permissions_check_access_by_billing_account_request,
    build_billing_permissions_check_access_by_billing_profile_request,
    build_billing_permissions_check_access_by_customer_request,
    build_billing_permissions_check_access_by_department_request,
    build_billing_permissions_check_access_by_enrollment_account_request,
    build_billing_permissions_check_access_by_invoice_section_request,
    build_billing_permissions_list_by_billing_account_request,
    build_billing_permissions_list_by_billing_profile_request,
    build_billing_permissions_list_by_customer_at_billing_account_request,
    build_billing_permissions_list_by_customer_request,
    build_billing_permissions_list_by_department_request,
    build_billing_permissions_list_by_enrollment_account_request,
    build_billing_permissions_list_by_invoice_section_request,
    build_billing_profiles_create_or_update_request,
    build_billing_profiles_delete_request,
    build_billing_profiles_get_request,
    build_billing_profiles_list_by_billing_account_request,
    build_billing_profiles_validate_delete_eligibility_request,
    build_billing_property_get_request,
    build_billing_property_update_request,
    build_billing_requests_create_or_update_request,
    build_billing_requests_get_request,
    build_billing_requests_list_by_billing_account_request,
    build_billing_requests_list_by_billing_profile_request,
    build_billing_requests_list_by_customer_request,
    build_billing_requests_list_by_invoice_section_request,
    build_billing_requests_list_by_user_request,
    build_billing_role_assignments_create_by_billing_account_request,
    build_billing_role_assignments_create_by_billing_profile_request,
    build_billing_role_assignments_create_by_customer_request,
    build_billing_role_assignments_create_by_invoice_section_request,
    build_billing_role_assignments_create_or_update_by_billing_account_request,
    build_billing_role_assignments_create_or_update_by_department_request,
    build_billing_role_assignments_create_or_update_by_enrollment_account_request,
    build_billing_role_assignments_delete_by_billing_account_request,
    build_billing_role_assignments_delete_by_billing_profile_request,
    build_billing_role_assignments_delete_by_customer_request,
    build_billing_role_assignments_delete_by_department_request,
    build_billing_role_assignments_delete_by_enrollment_account_request,
    build_billing_role_assignments_delete_by_invoice_section_request,
    build_billing_role_assignments_get_by_billing_account_request,
    build_billing_role_assignments_get_by_billing_profile_request,
    build_billing_role_assignments_get_by_customer_request,
    build_billing_role_assignments_get_by_department_request,
    build_billing_role_assignments_get_by_enrollment_account_request,
    build_billing_role_assignments_get_by_invoice_section_request,
    build_billing_role_assignments_list_by_billing_account_request,
    build_billing_role_assignments_list_by_billing_profile_request,
    build_billing_role_assignments_list_by_customer_request,
    build_billing_role_assignments_list_by_department_request,
    build_billing_role_assignments_list_by_enrollment_account_request,
    build_billing_role_assignments_list_by_invoice_section_request,
    build_billing_role_assignments_resolve_by_billing_account_request,
    build_billing_role_assignments_resolve_by_billing_profile_request,
    build_billing_role_assignments_resolve_by_customer_request,
    build_billing_role_assignments_resolve_by_invoice_section_request,
    build_billing_role_definition_get_by_billing_account_request,
    build_billing_role_definition_get_by_billing_profile_request,
    build_billing_role_definition_get_by_customer_request,
    build_billing_role_definition_get_by_department_request,
    build_billing_role_definition_get_by_enrollment_account_request,
    build_billing_role_definition_get_by_invoice_section_request,
    build_billing_role_definition_list_by_billing_account_request,
    build_billing_role_definition_list_by_billing_profile_request,
    build_billing_role_definition_list_by_customer_request,
    build_billing_role_definition_list_by_department_request,
    build_billing_role_definition_list_by_enrollment_account_request,
    build_billing_role_definition_list_by_invoice_section_request,
    build_billing_subscriptions_aliases_create_or_update_request,
    build_billing_subscriptions_aliases_get_request,
    build_billing_subscriptions_aliases_list_by_billing_account_request,
    build_billing_subscriptions_cancel_request,
    build_billing_subscriptions_delete_request,
    build_billing_subscriptions_get_by_billing_profile_request,
    build_billing_subscriptions_get_request,
    build_billing_subscriptions_list_by_billing_account_request,
    build_billing_subscriptions_list_by_billing_profile_request,
    build_billing_subscriptions_list_by_customer_at_billing_account_request,
    build_billing_subscriptions_list_by_customer_request,
    build_billing_subscriptions_list_by_enrollment_account_request,
    build_billing_subscriptions_list_by_invoice_section_request,
    build_billing_subscriptions_merge_request,
    build_billing_subscriptions_move_request,
    build_billing_subscriptions_split_request,
    build_billing_subscriptions_update_request,
    build_billing_subscriptions_validate_move_eligibility_request,
    build_customers_get_by_billing_account_request,
    build_customers_get_request,
    build_customers_list_by_billing_account_request,
    build_customers_list_by_billing_profile_request,
    build_departments_get_request,
    build_departments_list_by_billing_account_request,
    build_enrollment_accounts_get_by_department_request,
    build_enrollment_accounts_get_request,
    build_enrollment_accounts_list_by_billing_account_request,
    build_enrollment_accounts_list_by_department_request,
    build_invoice_sections_create_or_update_request,
    build_invoice_sections_delete_request,
    build_invoice_sections_get_request,
    build_invoice_sections_list_by_billing_profile_request,
    build_invoice_sections_validate_delete_eligibility_request,
    build_invoices_amend_request,
    build_invoices_download_by_billing_account_request,
    build_invoices_download_by_billing_subscription_request,
    build_invoices_download_documents_by_billing_account_request,
    build_invoices_download_documents_by_billing_subscription_request,
    build_invoices_download_summary_by_billing_account_request,
    build_invoices_get_by_billing_account_request,
    build_invoices_get_by_billing_subscription_request,
    build_invoices_get_request,
    build_invoices_list_by_billing_account_request,
    build_invoices_list_by_billing_profile_request,
    build_invoices_list_by_billing_subscription_request,
    build_operations_list_request,
    build_partner_transfers_cancel_request,
    build_partner_transfers_get_request,
    build_partner_transfers_initiate_request,
    build_partner_transfers_list_request,
    build_payment_methods_delete_by_user_request,
    build_payment_methods_get_by_billing_account_request,
    build_payment_methods_get_by_billing_profile_request,
    build_payment_methods_get_by_user_request,
    build_payment_methods_list_by_billing_account_request,
    build_payment_methods_list_by_billing_profile_request,
    build_payment_methods_list_by_user_request,
    build_policies_create_or_update_by_billing_account_request,
    build_policies_create_or_update_by_billing_profile_request,
    build_policies_create_or_update_by_customer_at_billing_account_request,
    build_policies_create_or_update_by_customer_request,
    build_policies_get_by_billing_account_request,
    build_policies_get_by_billing_profile_request,
    build_policies_get_by_customer_at_billing_account_request,
    build_policies_get_by_customer_request,
    build_policies_get_by_subscription_request,
    build_products_get_request,
    build_products_list_by_billing_account_request,
    build_products_list_by_billing_profile_request,
    build_products_list_by_customer_request,
    build_products_list_by_invoice_section_request,
    build_products_move_request,
    build_products_update_request,
    build_products_validate_move_eligibility_request,
    build_recipient_transfers_accept_request,
    build_recipient_transfers_decline_request,
    build_recipient_transfers_get_request,
    build_recipient_transfers_list_request,
    build_recipient_transfers_validate_request,
    build_reservation_orders_get_by_billing_account_request,
    build_reservation_orders_list_by_billing_account_request,
    build_reservations_get_by_reservation_order_request,
    build_reservations_list_by_billing_account_request,
    build_reservations_list_by_billing_profile_request,
    build_reservations_list_by_reservation_order_request,
    build_reservations_update_by_billing_account_request,
    build_savings_plan_orders_get_by_billing_account_request,
    build_savings_plan_orders_list_by_billing_account_request,
    build_savings_plans_get_by_billing_account_request,
    build_savings_plans_list_by_billing_account_request,
    build_savings_plans_list_by_savings_plan_order_request,
    build_savings_plans_update_by_billing_account_request,
    build_savings_plans_validate_update_by_billing_account_request,
    build_transactions_get_transaction_summary_by_invoice_request,
    build_transactions_list_by_billing_profile_request,
    build_transactions_list_by_customer_request,
    build_transactions_list_by_invoice_request,
    build_transactions_list_by_invoice_section_request,
    build_transactions_transactions_download_by_invoice_request,
    build_transfers_cancel_request,
    build_transfers_get_request,
    build_transfers_initiate_request,
    build_transfers_list_request,
)
from .._configuration import BillingManagementClientConfiguration

T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]]
JSON = MutableMapping[str, Any]
List = list


class Operations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s
        :attr:`operations` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: BillingManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list(self, **kwargs: Any) -> AsyncItemPaged["_models.Operation"]:
        """List of operations supported by provider.

        :return: An iterator like instance of Operation
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Operation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.Operation]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_operations_list_request(
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.Operation],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class AgreementsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s
        :attr:`agreements` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: BillingManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(self, billing_account_name: str, agreement_name: str, **kwargs: Any) -> _models.Agreement:
        """Gets an agreement by ID.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param agreement_name: The ID that uniquely identifies an agreement. Required.
        :type agreement_name: str
        :return: Agreement. The Agreement is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.Agreement
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.Agreement] = kwargs.pop("cls", None)

        _request = build_agreements_get_request(
            billing_account_name=billing_account_name,
            agreement_name=agreement_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.Agreement, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_billing_account(
        self, billing_account_name: str, *, expand: Optional[str] = None, **kwargs: Any
    ) -> AsyncItemPaged["_models.Agreement"]:
        """Lists the agreements for a billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :keyword expand: May be used to expand the participants. Default value is None.
        :paramtype expand: str
        :return: An iterator like instance of Agreement
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Agreement]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.Agreement]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_agreements_list_by_billing_account_request(
                    billing_account_name=billing_account_name,
                    expand=expand,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.Agreement],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class BillingRequestsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s
        :attr:`billing_requests` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: BillingManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(self, billing_request_name: str, **kwargs: Any) -> _models.BillingRequest:
        """Gets a billing request by its ID.

        :param billing_request_name: The ID that uniquely identifies a billing request. Required.
        :type billing_request_name: str
        :return: BillingRequest. The BillingRequest is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.BillingRequest
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.BillingRequest] = kwargs.pop("cls", None)

        _request = build_billing_requests_get_request(
            billing_request_name=billing_request_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.BillingRequest, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    async def _create_or_update_initial(
        self, billing_request_name: str, parameters: Union[_models.BillingRequest, JSON, IO[bytes]], **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_billing_requests_create_or_update_request(
            billing_request_name=billing_request_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 201:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_or_update(
        self,
        billing_request_name: str,
        parameters: _models.BillingRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRequest]:
        """Create or update a billing request.

        :param billing_request_name: The ID that uniquely identifies a billing request. Required.
        :type billing_request_name: str
        :param parameters: A request submitted by a user to manage billing. Users with an owner role on
         the scope can approve or decline these requests. Required.
        :type parameters: ~azure.mgmt.billing.models.BillingRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingRequest. The BillingRequest is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRequest]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self, billing_request_name: str, parameters: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRequest]:
        """Create or update a billing request.

        :param billing_request_name: The ID that uniquely identifies a billing request. Required.
        :type billing_request_name: str
        :param parameters: A request submitted by a user to manage billing. Users with an owner role on
         the scope can approve or decline these requests. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingRequest. The BillingRequest is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRequest]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self, billing_request_name: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRequest]:
        """Create or update a billing request.

        :param billing_request_name: The ID that uniquely identifies a billing request. Required.
        :type billing_request_name: str
        :param parameters: A request submitted by a user to manage billing. Users with an owner role on
         the scope can approve or decline these requests. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingRequest. The BillingRequest is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRequest]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_or_update(
        self, billing_request_name: str, parameters: Union[_models.BillingRequest, JSON, IO[bytes]], **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRequest]:
        """Create or update a billing request.

        :param billing_request_name: The ID that uniquely identifies a billing request. Required.
        :type billing_request_name: str
        :param parameters: A request submitted by a user to manage billing. Users with an owner role on
         the scope can approve or decline these requests. Is one of the following types: BillingRequest,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.BillingRequest or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns BillingRequest. The BillingRequest is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRequest]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.BillingRequest] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_or_update_initial(
                billing_request_name=billing_request_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.BillingRequest, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.BillingRequest].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.BillingRequest](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace
    def list_by_user(
        self,
        *,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        count: Optional[bool] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingRequest"]:
        """The list of billing requests submitted by a user.

        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :keyword count: The count query option allows clients to request a count of the matching
         resources included with the resources in the response. Default value is None.
        :paramtype count: bool
        :keyword search: The search query option allows clients to request items within a collection
         matching a free-text search expression. search is only supported for string fields. Default
         value is None.
        :paramtype search: str
        :return: An iterator like instance of BillingRequest
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRequest]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingRequest]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_requests_list_by_user_request(
                    filter=filter,
                    order_by=order_by,
                    top=top,
                    skip=skip,
                    count=count,
                    search=search,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingRequest],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_by_billing_account(
        self,
        billing_account_name: str,
        *,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        count: Optional[bool] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingRequest"]:
        """The list of billing requests submitted for the billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :keyword count: The count query option allows clients to request a count of the matching
         resources included with the resources in the response. Default value is None.
        :paramtype count: bool
        :keyword search: The search query option allows clients to request items within a collection
         matching a free-text search expression. search is only supported for string fields. Default
         value is None.
        :paramtype search: str
        :return: An iterator like instance of BillingRequest
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRequest]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingRequest]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_requests_list_by_billing_account_request(
                    billing_account_name=billing_account_name,
                    filter=filter,
                    order_by=order_by,
                    top=top,
                    skip=skip,
                    count=count,
                    search=search,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingRequest],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_by_billing_profile(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        *,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        count: Optional[bool] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingRequest"]:
        """The list of billing requests submitted for the billing profile.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :keyword count: The count query option allows clients to request a count of the matching
         resources included with the resources in the response. Default value is None.
        :paramtype count: bool
        :keyword search: The search query option allows clients to request items within a collection
         matching a free-text search expression. search is only supported for string fields. Default
         value is None.
        :paramtype search: str
        :return: An iterator like instance of BillingRequest
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRequest]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingRequest]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_requests_list_by_billing_profile_request(
                    billing_account_name=billing_account_name,
                    billing_profile_name=billing_profile_name,
                    filter=filter,
                    order_by=order_by,
                    top=top,
                    skip=skip,
                    count=count,
                    search=search,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingRequest],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_by_customer(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        customer_name: str,
        *,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        count: Optional[bool] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingRequest"]:
        """The list of billing requests submitted for the customer.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :keyword count: The count query option allows clients to request a count of the matching
         resources included with the resources in the response. Default value is None.
        :paramtype count: bool
        :keyword search: The search query option allows clients to request items within a collection
         matching a free-text search expression. search is only supported for string fields. Default
         value is None.
        :paramtype search: str
        :return: An iterator like instance of BillingRequest
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRequest]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingRequest]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_requests_list_by_customer_request(
                    billing_account_name=billing_account_name,
                    billing_profile_name=billing_profile_name,
                    customer_name=customer_name,
                    filter=filter,
                    order_by=order_by,
                    top=top,
                    skip=skip,
                    count=count,
                    search=search,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingRequest],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_by_invoice_section(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        invoice_section_name: str,
        *,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        count: Optional[bool] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingRequest"]:
        """The list of billing requests submitted for the invoice section.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :keyword count: The count query option allows clients to request a count of the matching
         resources included with the resources in the response. Default value is None.
        :paramtype count: bool
        :keyword search: The search query option allows clients to request items within a collection
         matching a free-text search expression. search is only supported for string fields. Default
         value is None.
        :paramtype search: str
        :return: An iterator like instance of BillingRequest
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRequest]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingRequest]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_requests_list_by_invoice_section_request(
                    billing_account_name=billing_account_name,
                    billing_profile_name=billing_profile_name,
                    invoice_section_name=invoice_section_name,
                    filter=filter,
                    order_by=order_by,
                    top=top,
                    skip=skip,
                    count=count,
                    search=search,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingRequest],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class BillingRoleAssignmentsOperations:  # pylint: disable=too-many-public-methods
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s
        :attr:`billing_role_assignments` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: BillingManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get_by_billing_profile(
        self, billing_account_name: str, billing_profile_name: str, billing_role_assignment_name: str, **kwargs: Any
    ) -> _models.BillingRoleAssignment:
        """Gets a role assignment for the caller on a billing profile. The operation is supported for
        billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer
        Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param billing_role_assignment_name: The ID that uniquely identifies a role assignment.
         Required.
        :type billing_role_assignment_name: str
        :return: BillingRoleAssignment. The BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.BillingRoleAssignment] = kwargs.pop("cls", None)

        _request = build_billing_role_assignments_get_by_billing_profile_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            billing_role_assignment_name=billing_role_assignment_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.BillingRoleAssignment, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete_by_billing_profile(
        self, billing_account_name: str, billing_profile_name: str, billing_role_assignment_name: str, **kwargs: Any
    ) -> None:
        """Deletes a role assignment on a billing profile. The operation is supported for billing accounts
        with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param billing_role_assignment_name: The ID that uniquely identifies a role assignment.
         Required.
        :type billing_role_assignment_name: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_billing_role_assignments_delete_by_billing_profile_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            billing_role_assignment_name=billing_role_assignment_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_billing_profile(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingRoleAssignment"]:
        """Lists the role assignments for the caller on a billing profile. The operation is supported for
        billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer
        Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of BillingRoleAssignment
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingRoleAssignment]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_role_assignments_list_by_billing_profile_request(
                    billing_account_name=billing_account_name,
                    billing_profile_name=billing_profile_name,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingRoleAssignment],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    async def _create_by_billing_account_initial(
        self,
        billing_account_name: str,
        parameters: Union[_models.BillingRoleAssignmentProperties, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_billing_role_assignments_create_by_billing_account_request(
            billing_account_name=billing_account_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_by_billing_account(
        self,
        billing_account_name: str,
        parameters: _models.BillingRoleAssignmentProperties,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRoleAssignment]:
        """Adds a role assignment on a billing account. The operation is supported for billing accounts
        with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param parameters: The properties of the billing role assignment. Required.
        :type parameters: ~azure.mgmt.billing.models.BillingRoleAssignmentProperties
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingRoleAssignment. The
         BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_by_billing_account(
        self, billing_account_name: str, parameters: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRoleAssignment]:
        """Adds a role assignment on a billing account. The operation is supported for billing accounts
        with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param parameters: The properties of the billing role assignment. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingRoleAssignment. The
         BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_by_billing_account(
        self, billing_account_name: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRoleAssignment]:
        """Adds a role assignment on a billing account. The operation is supported for billing accounts
        with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param parameters: The properties of the billing role assignment. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingRoleAssignment. The
         BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_by_billing_account(
        self,
        billing_account_name: str,
        parameters: Union[_models.BillingRoleAssignmentProperties, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRoleAssignment]:
        """Adds a role assignment on a billing account. The operation is supported for billing accounts
        with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param parameters: The properties of the billing role assignment. Is one of the following
         types: BillingRoleAssignmentProperties, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.BillingRoleAssignmentProperties or JSON or
         IO[bytes]
        :return: An instance of AsyncLROPoller that returns BillingRoleAssignment. The
         BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.BillingRoleAssignment] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_by_billing_account_initial(
                billing_account_name=billing_account_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.BillingRoleAssignment, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.BillingRoleAssignment].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.BillingRoleAssignment](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _resolve_by_billing_account_initial(
        self,
        billing_account_name: str,
        *,
        resolve_scope_display_names: bool = False,
        filter: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_billing_role_assignments_resolve_by_billing_account_request(
            billing_account_name=billing_account_name,
            resolve_scope_display_names=resolve_scope_display_names,
            filter=filter,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_resolve_by_billing_account(
        self,
        billing_account_name: str,
        *,
        resolve_scope_display_names: bool = False,
        filter: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRoleAssignmentListResult]:
        """Lists the role assignments for the caller on a billing account while fetching user info for
        each role assignment. The operation is supported for billing accounts with agreement type
        Microsoft Partner Agreement, Microsoft Customer Agreement or Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :keyword resolve_scope_display_names: Resolves the scope display name for each of the role
         assignments. Default value is False.
        :paramtype resolve_scope_display_names: bool
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :return: An instance of AsyncLROPoller that returns BillingRoleAssignmentListResult. The
         BillingRoleAssignmentListResult is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRoleAssignmentListResult]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.BillingRoleAssignmentListResult] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._resolve_by_billing_account_initial(
                billing_account_name=billing_account_name,
                resolve_scope_display_names=resolve_scope_display_names,
                filter=filter,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.BillingRoleAssignmentListResult, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.BillingRoleAssignmentListResult].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.BillingRoleAssignmentListResult](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _create_by_billing_profile_initial(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        parameters: Union[_models.BillingRoleAssignmentProperties, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_billing_role_assignments_create_by_billing_profile_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_by_billing_profile(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        parameters: _models.BillingRoleAssignmentProperties,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRoleAssignment]:
        """Adds a role assignment on a billing profile. The operation is supported for billing accounts
        with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param parameters: The properties of the billing role assignment. Required.
        :type parameters: ~azure.mgmt.billing.models.BillingRoleAssignmentProperties
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingRoleAssignment. The
         BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_by_billing_profile(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRoleAssignment]:
        """Adds a role assignment on a billing profile. The operation is supported for billing accounts
        with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param parameters: The properties of the billing role assignment. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingRoleAssignment. The
         BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_by_billing_profile(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRoleAssignment]:
        """Adds a role assignment on a billing profile. The operation is supported for billing accounts
        with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param parameters: The properties of the billing role assignment. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingRoleAssignment. The
         BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_by_billing_profile(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        parameters: Union[_models.BillingRoleAssignmentProperties, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRoleAssignment]:
        """Adds a role assignment on a billing profile. The operation is supported for billing accounts
        with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param parameters: The properties of the billing role assignment. Is one of the following
         types: BillingRoleAssignmentProperties, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.BillingRoleAssignmentProperties or JSON or
         IO[bytes]
        :return: An instance of AsyncLROPoller that returns BillingRoleAssignment. The
         BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.BillingRoleAssignment] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_by_billing_profile_initial(
                billing_account_name=billing_account_name,
                billing_profile_name=billing_profile_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.BillingRoleAssignment, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.BillingRoleAssignment].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.BillingRoleAssignment](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _resolve_by_billing_profile_initial(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        *,
        resolve_scope_display_names: bool = False,
        filter: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_billing_role_assignments_resolve_by_billing_profile_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            resolve_scope_display_names=resolve_scope_display_names,
            filter=filter,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_resolve_by_billing_profile(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        *,
        resolve_scope_display_names: bool = False,
        filter: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRoleAssignmentListResult]:
        """Lists the role assignments for the caller on an billing profile while fetching user info for
        each role assignment. The operation is supported for billing accounts with agreement type
        Microsoft Partner Agreement or Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :keyword resolve_scope_display_names: Resolves the scope display name for each of the role
         assignments. Default value is False.
        :paramtype resolve_scope_display_names: bool
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :return: An instance of AsyncLROPoller that returns BillingRoleAssignmentListResult. The
         BillingRoleAssignmentListResult is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRoleAssignmentListResult]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.BillingRoleAssignmentListResult] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._resolve_by_billing_profile_initial(
                billing_account_name=billing_account_name,
                billing_profile_name=billing_profile_name,
                resolve_scope_display_names=resolve_scope_display_names,
                filter=filter,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.BillingRoleAssignmentListResult, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.BillingRoleAssignmentListResult].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.BillingRoleAssignmentListResult](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace_async
    async def get_by_customer(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        customer_name: str,
        billing_role_assignment_name: str,
        **kwargs: Any
    ) -> _models.BillingRoleAssignment:
        """Gets a role assignment for the caller on a customer. The operation is supported for billing
        accounts with agreement type Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :param billing_role_assignment_name: The ID that uniquely identifies a role assignment.
         Required.
        :type billing_role_assignment_name: str
        :return: BillingRoleAssignment. The BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.BillingRoleAssignment] = kwargs.pop("cls", None)

        _request = build_billing_role_assignments_get_by_customer_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            customer_name=customer_name,
            billing_role_assignment_name=billing_role_assignment_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.BillingRoleAssignment, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete_by_customer(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        customer_name: str,
        billing_role_assignment_name: str,
        **kwargs: Any
    ) -> None:
        """Deletes a role assignment on a customer. The operation is supported for billing accounts with
        agreement type Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :param billing_role_assignment_name: The ID that uniquely identifies a role assignment.
         Required.
        :type billing_role_assignment_name: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_billing_role_assignments_delete_by_customer_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            customer_name=customer_name,
            billing_role_assignment_name=billing_role_assignment_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_customer(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        customer_name: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingRoleAssignment"]:
        """Lists the role assignments for the caller on customer. The operation is supported for billing
        accounts with agreement type Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of BillingRoleAssignment
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingRoleAssignment]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_role_assignments_list_by_customer_request(
                    billing_account_name=billing_account_name,
                    billing_profile_name=billing_profile_name,
                    customer_name=customer_name,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingRoleAssignment],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def get_by_invoice_section(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        invoice_section_name: str,
        billing_role_assignment_name: str,
        **kwargs: Any
    ) -> _models.BillingRoleAssignment:
        """Gets a role assignment for the caller on an invoice section. The operation is supported for
        billing accounts with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :param billing_role_assignment_name: The ID that uniquely identifies a role assignment.
         Required.
        :type billing_role_assignment_name: str
        :return: BillingRoleAssignment. The BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.BillingRoleAssignment] = kwargs.pop("cls", None)

        _request = build_billing_role_assignments_get_by_invoice_section_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            invoice_section_name=invoice_section_name,
            billing_role_assignment_name=billing_role_assignment_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.BillingRoleAssignment, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete_by_invoice_section(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        invoice_section_name: str,
        billing_role_assignment_name: str,
        **kwargs: Any
    ) -> None:
        """Deletes a role assignment on an invoice section. The operation is supported for billing
        accounts with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :param billing_role_assignment_name: The ID that uniquely identifies a role assignment.
         Required.
        :type billing_role_assignment_name: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_billing_role_assignments_delete_by_invoice_section_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            invoice_section_name=invoice_section_name,
            billing_role_assignment_name=billing_role_assignment_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_invoice_section(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        invoice_section_name: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingRoleAssignment"]:
        """Lists the role assignments for the caller on an invoice section. The operation is supported for
        billing accounts with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of BillingRoleAssignment
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingRoleAssignment]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_role_assignments_list_by_invoice_section_request(
                    billing_account_name=billing_account_name,
                    billing_profile_name=billing_profile_name,
                    invoice_section_name=invoice_section_name,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingRoleAssignment],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def get_by_billing_account(
        self, billing_account_name: str, billing_role_assignment_name: str, **kwargs: Any
    ) -> _models.BillingRoleAssignment:
        """Gets a role assignment for the caller on a billing account. The operation is supported for
        billing accounts with agreement type Microsoft Partner Agreement, Microsoft Customer Agreement
        or Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_role_assignment_name: The ID that uniquely identifies a role assignment.
         Required.
        :type billing_role_assignment_name: str
        :return: BillingRoleAssignment. The BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.BillingRoleAssignment] = kwargs.pop("cls", None)

        _request = build_billing_role_assignments_get_by_billing_account_request(
            billing_account_name=billing_account_name,
            billing_role_assignment_name=billing_role_assignment_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.BillingRoleAssignment, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    async def _create_or_update_by_billing_account_initial(  # pylint: disable=name-too-long
        self,
        billing_account_name: str,
        billing_role_assignment_name: str,
        parameters: Union[_models.BillingRoleAssignment, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_billing_role_assignments_create_or_update_by_billing_account_request(
            billing_account_name=billing_account_name,
            billing_role_assignment_name=billing_role_assignment_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 201:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_or_update_by_billing_account(  # pylint: disable=name-too-long
        self,
        billing_account_name: str,
        billing_role_assignment_name: str,
        parameters: _models.BillingRoleAssignment,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRoleAssignment]:
        """Create or update a billing role assignment. The operation is supported only for billing
        accounts with agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_role_assignment_name: The ID that uniquely identifies a role assignment.
         Required.
        :type billing_role_assignment_name: str
        :param parameters: The properties of the billing role assignment. Required.
        :type parameters: ~azure.mgmt.billing.models.BillingRoleAssignment
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingRoleAssignment. The
         BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update_by_billing_account(  # pylint: disable=name-too-long
        self,
        billing_account_name: str,
        billing_role_assignment_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRoleAssignment]:
        """Create or update a billing role assignment. The operation is supported only for billing
        accounts with agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_role_assignment_name: The ID that uniquely identifies a role assignment.
         Required.
        :type billing_role_assignment_name: str
        :param parameters: The properties of the billing role assignment. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingRoleAssignment. The
         BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update_by_billing_account(  # pylint: disable=name-too-long
        self,
        billing_account_name: str,
        billing_role_assignment_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRoleAssignment]:
        """Create or update a billing role assignment. The operation is supported only for billing
        accounts with agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_role_assignment_name: The ID that uniquely identifies a role assignment.
         Required.
        :type billing_role_assignment_name: str
        :param parameters: The properties of the billing role assignment. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingRoleAssignment. The
         BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_or_update_by_billing_account(  # pylint: disable=name-too-long
        self,
        billing_account_name: str,
        billing_role_assignment_name: str,
        parameters: Union[_models.BillingRoleAssignment, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRoleAssignment]:
        """Create or update a billing role assignment. The operation is supported only for billing
        accounts with agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_role_assignment_name: The ID that uniquely identifies a role assignment.
         Required.
        :type billing_role_assignment_name: str
        :param parameters: The properties of the billing role assignment. Is one of the following
         types: BillingRoleAssignment, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.BillingRoleAssignment or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns BillingRoleAssignment. The
         BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.BillingRoleAssignment] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_or_update_by_billing_account_initial(
                billing_account_name=billing_account_name,
                billing_role_assignment_name=billing_role_assignment_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.BillingRoleAssignment, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.BillingRoleAssignment].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.BillingRoleAssignment](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace_async
    async def delete_by_billing_account(
        self, billing_account_name: str, billing_role_assignment_name: str, **kwargs: Any
    ) -> None:
        """Deletes a role assignment on a billing account. The operation is supported for billing accounts
        with agreement type Microsoft Partner Agreement, Microsoft Customer Agreement or Enterprise
        Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_role_assignment_name: The ID that uniquely identifies a role assignment.
         Required.
        :type billing_role_assignment_name: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_billing_role_assignments_delete_by_billing_account_request(
            billing_account_name=billing_account_name,
            billing_role_assignment_name=billing_role_assignment_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_billing_account(
        self,
        billing_account_name: str,
        *,
        filter: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingRoleAssignment"]:
        """Lists the role assignments for the caller on a billing account. The operation is supported for
        billing accounts with agreement type Microsoft Partner Agreement, Microsoft Customer Agreement
        or Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :return: An iterator like instance of BillingRoleAssignment
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingRoleAssignment]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_role_assignments_list_by_billing_account_request(
                    billing_account_name=billing_account_name,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingRoleAssignment],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def get_by_department(
        self, billing_account_name: str, department_name: str, billing_role_assignment_name: str, **kwargs: Any
    ) -> _models.BillingRoleAssignment:
        """Gets a role assignment for the caller on a department. The operation is supported only for
        billing accounts with agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param department_name: The name of the department. Required.
        :type department_name: str
        :param billing_role_assignment_name: The ID that uniquely identifies a role assignment.
         Required.
        :type billing_role_assignment_name: str
        :return: BillingRoleAssignment. The BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.BillingRoleAssignment] = kwargs.pop("cls", None)

        _request = build_billing_role_assignments_get_by_department_request(
            billing_account_name=billing_account_name,
            department_name=department_name,
            billing_role_assignment_name=billing_role_assignment_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.BillingRoleAssignment, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    async def _create_or_update_by_department_initial(
        self,
        billing_account_name: str,
        department_name: str,
        billing_role_assignment_name: str,
        parameters: Union[_models.BillingRoleAssignment, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_billing_role_assignments_create_or_update_by_department_request(
            billing_account_name=billing_account_name,
            department_name=department_name,
            billing_role_assignment_name=billing_role_assignment_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 201:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_or_update_by_department(
        self,
        billing_account_name: str,
        department_name: str,
        billing_role_assignment_name: str,
        parameters: _models.BillingRoleAssignment,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRoleAssignment]:
        """Create or update a billing role assignment. The operation is supported only for billing
        accounts with agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param department_name: The name of the department. Required.
        :type department_name: str
        :param billing_role_assignment_name: The ID that uniquely identifies a role assignment.
         Required.
        :type billing_role_assignment_name: str
        :param parameters: The properties of the billing role assignment. Required.
        :type parameters: ~azure.mgmt.billing.models.BillingRoleAssignment
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingRoleAssignment. The
         BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update_by_department(
        self,
        billing_account_name: str,
        department_name: str,
        billing_role_assignment_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRoleAssignment]:
        """Create or update a billing role assignment. The operation is supported only for billing
        accounts with agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param department_name: The name of the department. Required.
        :type department_name: str
        :param billing_role_assignment_name: The ID that uniquely identifies a role assignment.
         Required.
        :type billing_role_assignment_name: str
        :param parameters: The properties of the billing role assignment. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingRoleAssignment. The
         BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update_by_department(
        self,
        billing_account_name: str,
        department_name: str,
        billing_role_assignment_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRoleAssignment]:
        """Create or update a billing role assignment. The operation is supported only for billing
        accounts with agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param department_name: The name of the department. Required.
        :type department_name: str
        :param billing_role_assignment_name: The ID that uniquely identifies a role assignment.
         Required.
        :type billing_role_assignment_name: str
        :param parameters: The properties of the billing role assignment. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingRoleAssignment. The
         BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_or_update_by_department(
        self,
        billing_account_name: str,
        department_name: str,
        billing_role_assignment_name: str,
        parameters: Union[_models.BillingRoleAssignment, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRoleAssignment]:
        """Create or update a billing role assignment. The operation is supported only for billing
        accounts with agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param department_name: The name of the department. Required.
        :type department_name: str
        :param billing_role_assignment_name: The ID that uniquely identifies a role assignment.
         Required.
        :type billing_role_assignment_name: str
        :param parameters: The properties of the billing role assignment. Is one of the following
         types: BillingRoleAssignment, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.BillingRoleAssignment or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns BillingRoleAssignment. The
         BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.BillingRoleAssignment] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_or_update_by_department_initial(
                billing_account_name=billing_account_name,
                department_name=department_name,
                billing_role_assignment_name=billing_role_assignment_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.BillingRoleAssignment, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.BillingRoleAssignment].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.BillingRoleAssignment](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace_async
    async def delete_by_department(
        self, billing_account_name: str, department_name: str, billing_role_assignment_name: str, **kwargs: Any
    ) -> None:
        """Deletes a role assignment on a department. The operation is supported only for billing accounts
        with agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param department_name: The name of the department. Required.
        :type department_name: str
        :param billing_role_assignment_name: The ID that uniquely identifies a role assignment.
         Required.
        :type billing_role_assignment_name: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_billing_role_assignments_delete_by_department_request(
            billing_account_name=billing_account_name,
            department_name=department_name,
            billing_role_assignment_name=billing_role_assignment_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_department(
        self, billing_account_name: str, department_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingRoleAssignment"]:
        """Lists the role assignments for the caller on a department. The operation is supported for
        billing accounts of type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param department_name: The name of the department. Required.
        :type department_name: str
        :return: An iterator like instance of BillingRoleAssignment
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingRoleAssignment]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_role_assignments_list_by_department_request(
                    billing_account_name=billing_account_name,
                    department_name=department_name,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingRoleAssignment],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def get_by_enrollment_account(
        self, billing_account_name: str, enrollment_account_name: str, billing_role_assignment_name: str, **kwargs: Any
    ) -> _models.BillingRoleAssignment:
        """Gets a role assignment for the caller on a enrollment Account. The operation is supported only
        for billing accounts with agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param enrollment_account_name: The name of the enrollment account. Required.
        :type enrollment_account_name: str
        :param billing_role_assignment_name: The ID that uniquely identifies a role assignment.
         Required.
        :type billing_role_assignment_name: str
        :return: BillingRoleAssignment. The BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.BillingRoleAssignment] = kwargs.pop("cls", None)

        _request = build_billing_role_assignments_get_by_enrollment_account_request(
            billing_account_name=billing_account_name,
            enrollment_account_name=enrollment_account_name,
            billing_role_assignment_name=billing_role_assignment_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.BillingRoleAssignment, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    async def _create_or_update_by_enrollment_account_initial(  # pylint: disable=name-too-long
        self,
        billing_account_name: str,
        enrollment_account_name: str,
        billing_role_assignment_name: str,
        parameters: Union[_models.BillingRoleAssignment, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_billing_role_assignments_create_or_update_by_enrollment_account_request(
            billing_account_name=billing_account_name,
            enrollment_account_name=enrollment_account_name,
            billing_role_assignment_name=billing_role_assignment_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 201:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_or_update_by_enrollment_account(  # pylint: disable=name-too-long
        self,
        billing_account_name: str,
        enrollment_account_name: str,
        billing_role_assignment_name: str,
        parameters: _models.BillingRoleAssignment,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRoleAssignment]:
        """Create or update a billing role assignment. The operation is supported only for billing
        accounts with agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param enrollment_account_name: The name of the enrollment account. Required.
        :type enrollment_account_name: str
        :param billing_role_assignment_name: The ID that uniquely identifies a role assignment.
         Required.
        :type billing_role_assignment_name: str
        :param parameters: The properties of the billing role assignment. Required.
        :type parameters: ~azure.mgmt.billing.models.BillingRoleAssignment
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingRoleAssignment. The
         BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update_by_enrollment_account(  # pylint: disable=name-too-long
        self,
        billing_account_name: str,
        enrollment_account_name: str,
        billing_role_assignment_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRoleAssignment]:
        """Create or update a billing role assignment. The operation is supported only for billing
        accounts with agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param enrollment_account_name: The name of the enrollment account. Required.
        :type enrollment_account_name: str
        :param billing_role_assignment_name: The ID that uniquely identifies a role assignment.
         Required.
        :type billing_role_assignment_name: str
        :param parameters: The properties of the billing role assignment. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingRoleAssignment. The
         BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update_by_enrollment_account(  # pylint: disable=name-too-long
        self,
        billing_account_name: str,
        enrollment_account_name: str,
        billing_role_assignment_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRoleAssignment]:
        """Create or update a billing role assignment. The operation is supported only for billing
        accounts with agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param enrollment_account_name: The name of the enrollment account. Required.
        :type enrollment_account_name: str
        :param billing_role_assignment_name: The ID that uniquely identifies a role assignment.
         Required.
        :type billing_role_assignment_name: str
        :param parameters: The properties of the billing role assignment. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingRoleAssignment. The
         BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_or_update_by_enrollment_account(  # pylint: disable=name-too-long
        self,
        billing_account_name: str,
        enrollment_account_name: str,
        billing_role_assignment_name: str,
        parameters: Union[_models.BillingRoleAssignment, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRoleAssignment]:
        """Create or update a billing role assignment. The operation is supported only for billing
        accounts with agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param enrollment_account_name: The name of the enrollment account. Required.
        :type enrollment_account_name: str
        :param billing_role_assignment_name: The ID that uniquely identifies a role assignment.
         Required.
        :type billing_role_assignment_name: str
        :param parameters: The properties of the billing role assignment. Is one of the following
         types: BillingRoleAssignment, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.BillingRoleAssignment or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns BillingRoleAssignment. The
         BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.BillingRoleAssignment] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_or_update_by_enrollment_account_initial(
                billing_account_name=billing_account_name,
                enrollment_account_name=enrollment_account_name,
                billing_role_assignment_name=billing_role_assignment_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.BillingRoleAssignment, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.BillingRoleAssignment].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.BillingRoleAssignment](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace_async
    async def delete_by_enrollment_account(
        self, billing_account_name: str, enrollment_account_name: str, billing_role_assignment_name: str, **kwargs: Any
    ) -> None:
        """Deletes a role assignment on a enrollment Account. The operation is supported only for billing
        accounts with agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param enrollment_account_name: The name of the enrollment account. Required.
        :type enrollment_account_name: str
        :param billing_role_assignment_name: The ID that uniquely identifies a role assignment.
         Required.
        :type billing_role_assignment_name: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_billing_role_assignments_delete_by_enrollment_account_request(
            billing_account_name=billing_account_name,
            enrollment_account_name=enrollment_account_name,
            billing_role_assignment_name=billing_role_assignment_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_enrollment_account(
        self, billing_account_name: str, enrollment_account_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingRoleAssignment"]:
        """Lists the role assignments for the caller on a enrollment account. The operation is supported
        for billing accounts of type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param enrollment_account_name: The name of the enrollment account. Required.
        :type enrollment_account_name: str
        :return: An iterator like instance of BillingRoleAssignment
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingRoleAssignment]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_role_assignments_list_by_enrollment_account_request(
                    billing_account_name=billing_account_name,
                    enrollment_account_name=enrollment_account_name,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingRoleAssignment],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    async def _create_by_customer_initial(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        customer_name: str,
        parameters: Union[_models.BillingRoleAssignmentProperties, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_billing_role_assignments_create_by_customer_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            customer_name=customer_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_by_customer(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        customer_name: str,
        parameters: _models.BillingRoleAssignmentProperties,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRoleAssignment]:
        """Adds a role assignment on a customer. The operation is supported for billing accounts with
        agreement type Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :param parameters: The properties of the billing role assignment. Required.
        :type parameters: ~azure.mgmt.billing.models.BillingRoleAssignmentProperties
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingRoleAssignment. The
         BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_by_customer(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        customer_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRoleAssignment]:
        """Adds a role assignment on a customer. The operation is supported for billing accounts with
        agreement type Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :param parameters: The properties of the billing role assignment. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingRoleAssignment. The
         BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_by_customer(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        customer_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRoleAssignment]:
        """Adds a role assignment on a customer. The operation is supported for billing accounts with
        agreement type Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :param parameters: The properties of the billing role assignment. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingRoleAssignment. The
         BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_by_customer(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        customer_name: str,
        parameters: Union[_models.BillingRoleAssignmentProperties, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRoleAssignment]:
        """Adds a role assignment on a customer. The operation is supported for billing accounts with
        agreement type Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :param parameters: The properties of the billing role assignment. Is one of the following
         types: BillingRoleAssignmentProperties, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.BillingRoleAssignmentProperties or JSON or
         IO[bytes]
        :return: An instance of AsyncLROPoller that returns BillingRoleAssignment. The
         BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.BillingRoleAssignment] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_by_customer_initial(
                billing_account_name=billing_account_name,
                billing_profile_name=billing_profile_name,
                customer_name=customer_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.BillingRoleAssignment, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.BillingRoleAssignment].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.BillingRoleAssignment](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _resolve_by_customer_initial(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        customer_name: str,
        *,
        resolve_scope_display_names: bool = False,
        filter: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_billing_role_assignments_resolve_by_customer_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            customer_name=customer_name,
            resolve_scope_display_names=resolve_scope_display_names,
            filter=filter,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_resolve_by_customer(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        customer_name: str,
        *,
        resolve_scope_display_names: bool = False,
        filter: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRoleAssignmentListResult]:
        """Lists the role assignments for the caller on a customer while fetching user info for each role
        assignment. The operation is supported for billing accounts with agreement type Microsoft
        Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :keyword resolve_scope_display_names: Resolves the scope display name for each of the role
         assignments. Default value is False.
        :paramtype resolve_scope_display_names: bool
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :return: An instance of AsyncLROPoller that returns BillingRoleAssignmentListResult. The
         BillingRoleAssignmentListResult is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRoleAssignmentListResult]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.BillingRoleAssignmentListResult] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._resolve_by_customer_initial(
                billing_account_name=billing_account_name,
                billing_profile_name=billing_profile_name,
                customer_name=customer_name,
                resolve_scope_display_names=resolve_scope_display_names,
                filter=filter,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.BillingRoleAssignmentListResult, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.BillingRoleAssignmentListResult].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.BillingRoleAssignmentListResult](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _create_by_invoice_section_initial(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        invoice_section_name: str,
        parameters: Union[_models.BillingRoleAssignmentProperties, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_billing_role_assignments_create_by_invoice_section_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            invoice_section_name=invoice_section_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_by_invoice_section(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        invoice_section_name: str,
        parameters: _models.BillingRoleAssignmentProperties,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRoleAssignment]:
        """Adds a role assignment on an invoice section. The operation is supported for billing accounts
        with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :param parameters: The properties of the billing role assignment. Required.
        :type parameters: ~azure.mgmt.billing.models.BillingRoleAssignmentProperties
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingRoleAssignment. The
         BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_by_invoice_section(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        invoice_section_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRoleAssignment]:
        """Adds a role assignment on an invoice section. The operation is supported for billing accounts
        with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :param parameters: The properties of the billing role assignment. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingRoleAssignment. The
         BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_by_invoice_section(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        invoice_section_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRoleAssignment]:
        """Adds a role assignment on an invoice section. The operation is supported for billing accounts
        with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :param parameters: The properties of the billing role assignment. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingRoleAssignment. The
         BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_by_invoice_section(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        invoice_section_name: str,
        parameters: Union[_models.BillingRoleAssignmentProperties, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRoleAssignment]:
        """Adds a role assignment on an invoice section. The operation is supported for billing accounts
        with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :param parameters: The properties of the billing role assignment. Is one of the following
         types: BillingRoleAssignmentProperties, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.BillingRoleAssignmentProperties or JSON or
         IO[bytes]
        :return: An instance of AsyncLROPoller that returns BillingRoleAssignment. The
         BillingRoleAssignment is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRoleAssignment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.BillingRoleAssignment] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_by_invoice_section_initial(
                billing_account_name=billing_account_name,
                billing_profile_name=billing_profile_name,
                invoice_section_name=invoice_section_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.BillingRoleAssignment, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.BillingRoleAssignment].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.BillingRoleAssignment](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _resolve_by_invoice_section_initial(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        invoice_section_name: str,
        *,
        resolve_scope_display_names: bool = False,
        filter: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_billing_role_assignments_resolve_by_invoice_section_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            invoice_section_name=invoice_section_name,
            resolve_scope_display_names=resolve_scope_display_names,
            filter=filter,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_resolve_by_invoice_section(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        invoice_section_name: str,
        *,
        resolve_scope_display_names: bool = False,
        filter: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingRoleAssignmentListResult]:
        """Lists the role assignments for the caller on an invoice section while fetching user info for
        each role assignment. The operation is supported for billing accounts with agreement type
        Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :keyword resolve_scope_display_names: Resolves the scope display name for each of the role
         assignments. Default value is False.
        :paramtype resolve_scope_display_names: bool
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :return: An instance of AsyncLROPoller that returns BillingRoleAssignmentListResult. The
         BillingRoleAssignmentListResult is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingRoleAssignmentListResult]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.BillingRoleAssignmentListResult] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._resolve_by_invoice_section_initial(
                billing_account_name=billing_account_name,
                billing_profile_name=billing_profile_name,
                invoice_section_name=invoice_section_name,
                resolve_scope_display_names=resolve_scope_display_names,
                filter=filter,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.BillingRoleAssignmentListResult, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.BillingRoleAssignmentListResult].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.BillingRoleAssignmentListResult](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )


class InvoicesOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s
        :attr:`invoices` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: BillingManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get_by_billing_account(
        self, billing_account_name: str, invoice_name: str, **kwargs: Any
    ) -> _models.Invoice:
        """Gets an invoice by billing account name and ID. The operation is supported for all billing
        account types.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param invoice_name: The ID that uniquely identifies an invoice. Required.
        :type invoice_name: str
        :return: Invoice. The Invoice is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.Invoice
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.Invoice] = kwargs.pop("cls", None)

        _request = build_invoices_get_by_billing_account_request(
            billing_account_name=billing_account_name,
            invoice_name=invoice_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.Invoice, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_billing_account(
        self,
        billing_account_name: str,
        *,
        period_start_date: Optional[datetime.date] = None,
        period_end_date: Optional[datetime.date] = None,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        count: Optional[bool] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.Invoice"]:
        """Lists the invoices for a billing account for a given start date and end date. The operation is
        supported for all billing account types.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :keyword period_start_date: The start date of the billing period for which the invoice is
         generated. The date is in MM-DD-YYYY format. Default value is None.
        :paramtype period_start_date: ~datetime.date
        :keyword period_end_date: The end date of the billing period for which the invoice is
         generated. The date is in MM-DD-YYYY format. Default value is None.
        :paramtype period_end_date: ~datetime.date
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :keyword count: The count query option allows clients to request a count of the matching
         resources included with the resources in the response. Default value is None.
        :paramtype count: bool
        :keyword search: The search query option allows clients to request items within a collection
         matching a free-text search expression. search is only supported for string fields. Default
         value is None.
        :paramtype search: str
        :return: An iterator like instance of Invoice
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Invoice]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.Invoice]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_invoices_list_by_billing_account_request(
                    billing_account_name=billing_account_name,
                    period_start_date=period_start_date,
                    period_end_date=period_end_date,
                    filter=filter,
                    order_by=order_by,
                    top=top,
                    skip=skip,
                    count=count,
                    search=search,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.Invoice],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    async def _amend_initial(self, billing_account_name: str, invoice_name: str, **kwargs: Any) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_invoices_amend_request(
            billing_account_name=billing_account_name,
            invoice_name=invoice_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
        response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_amend(self, billing_account_name: str, invoice_name: str, **kwargs: Any) -> AsyncLROPoller[None]:
        """Regenerate an invoice by billing account name and invoice name. The operation is supported for
        billing accounts with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param invoice_name: The ID that uniquely identifies an invoice. Required.
        :type invoice_name: str
        :return: An instance of AsyncLROPoller that returns None
        :rtype: ~azure.core.polling.AsyncLROPoller[None]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._amend_initial(
                billing_account_name=billing_account_name,
                invoice_name=invoice_name,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):  # pylint: disable=inconsistent-return-statements
            if cls:
                return cls(pipeline_response, None, {})  # type: ignore

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[None].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method)  # type: ignore

    async def _download_by_billing_account_initial(
        self, billing_account_name: str, invoice_name: str, *, document_name: Optional[str] = None, **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_invoices_download_by_billing_account_request(
            billing_account_name=billing_account_name,
            invoice_name=invoice_name,
            document_name=document_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_download_by_billing_account(
        self, billing_account_name: str, invoice_name: str, *, document_name: Optional[str] = None, **kwargs: Any
    ) -> AsyncLROPoller[_models.DocumentDownloadResult]:
        """Gets a URL to download an invoice document. The operation is supported for billing accounts
        with agreement type Microsoft Partner Agreement, Microsoft Customer Agreement or Enterprise
        Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param invoice_name: The ID that uniquely identifies an invoice. Required.
        :type invoice_name: str
        :keyword document_name: The ID that uniquely identifies an invoice document. This ID may be an
         identifier for an invoice PDF, a credit note, or a tax receipt. Default value is None.
        :paramtype document_name: str
        :return: An instance of AsyncLROPoller that returns DocumentDownloadResult. The
         DocumentDownloadResult is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DocumentDownloadResult]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.DocumentDownloadResult] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._download_by_billing_account_initial(
                billing_account_name=billing_account_name,
                invoice_name=invoice_name,
                document_name=document_name,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.DocumentDownloadResult, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.DocumentDownloadResult].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.DocumentDownloadResult](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _download_summary_by_billing_account_initial(  # pylint: disable=name-too-long
        self, billing_account_name: str, invoice_name: str, **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_invoices_download_summary_by_billing_account_request(
            billing_account_name=billing_account_name,
            invoice_name=invoice_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_download_summary_by_billing_account(  # pylint: disable=name-too-long
        self, billing_account_name: str, invoice_name: str, **kwargs: Any
    ) -> AsyncLROPoller[_models.DocumentDownloadResult]:
        """Gets a URL to download the summary document for an invoice. The operation is supported for
        billing accounts with agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param invoice_name: The ID that uniquely identifies an invoice. Required.
        :type invoice_name: str
        :return: An instance of AsyncLROPoller that returns DocumentDownloadResult. The
         DocumentDownloadResult is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DocumentDownloadResult]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.DocumentDownloadResult] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._download_summary_by_billing_account_initial(
                billing_account_name=billing_account_name,
                invoice_name=invoice_name,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.DocumentDownloadResult, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.DocumentDownloadResult].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.DocumentDownloadResult](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _download_documents_by_billing_account_initial(  # pylint: disable=name-too-long
        self,
        billing_account_name: str,
        parameters: Union[List[_models.DocumentDownloadRequest], List[JSON], IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_invoices_download_documents_by_billing_account_request(
            billing_account_name=billing_account_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_download_documents_by_billing_account(  # pylint: disable=name-too-long
        self,
        billing_account_name: str,
        parameters: List[_models.DocumentDownloadRequest],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.DocumentDownloadResult]:
        """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as
        a zip file. The operation is supported for billing accounts with agreement type Microsoft
        Partner Agreement or Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param parameters: A list of download details for individual documents. Required.
        :type parameters: list[~azure.mgmt.billing.models.DocumentDownloadRequest]
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns DocumentDownloadResult. The
         DocumentDownloadResult is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DocumentDownloadResult]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_download_documents_by_billing_account(  # pylint: disable=name-too-long
        self,
        billing_account_name: str,
        parameters: List[JSON],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.DocumentDownloadResult]:
        """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as
        a zip file. The operation is supported for billing accounts with agreement type Microsoft
        Partner Agreement or Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param parameters: A list of download details for individual documents. Required.
        :type parameters: list[JSON]
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns DocumentDownloadResult. The
         DocumentDownloadResult is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DocumentDownloadResult]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_download_documents_by_billing_account(  # pylint: disable=name-too-long
        self, billing_account_name: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any
    ) -> AsyncLROPoller[_models.DocumentDownloadResult]:
        """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as
        a zip file. The operation is supported for billing accounts with agreement type Microsoft
        Partner Agreement or Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param parameters: A list of download details for individual documents. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns DocumentDownloadResult. The
         DocumentDownloadResult is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DocumentDownloadResult]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_download_documents_by_billing_account(  # pylint: disable=name-too-long
        self,
        billing_account_name: str,
        parameters: Union[List[_models.DocumentDownloadRequest], List[JSON], IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.DocumentDownloadResult]:
        """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as
        a zip file. The operation is supported for billing accounts with agreement type Microsoft
        Partner Agreement or Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param parameters: A list of download details for individual documents. Is one of the following
         types: [DocumentDownloadRequest], [JSON], IO[bytes] Required.
        :type parameters: list[~azure.mgmt.billing.models.DocumentDownloadRequest] or list[JSON] or
         IO[bytes]
        :return: An instance of AsyncLROPoller that returns DocumentDownloadResult. The
         DocumentDownloadResult is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DocumentDownloadResult]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.DocumentDownloadResult] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._download_documents_by_billing_account_initial(
                billing_account_name=billing_account_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.DocumentDownloadResult, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.DocumentDownloadResult].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.DocumentDownloadResult](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace
    def list_by_billing_profile(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        *,
        period_start_date: Optional[datetime.date] = None,
        period_end_date: Optional[datetime.date] = None,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        count: Optional[bool] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.Invoice"]:
        """Lists the invoices for a billing profile for a given start date and end date. The operation is
        supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft
        Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :keyword period_start_date: The start date of the billing period for which the invoice is
         generated. The date is in MM-DD-YYYY format. Default value is None.
        :paramtype period_start_date: ~datetime.date
        :keyword period_end_date: The end date of the billing period for which the invoice is
         generated. The date is in MM-DD-YYYY format. Default value is None.
        :paramtype period_end_date: ~datetime.date
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :keyword count: The count query option allows clients to request a count of the matching
         resources included with the resources in the response. Default value is None.
        :paramtype count: bool
        :keyword search: The search query option allows clients to request items within a collection
         matching a free-text search expression. search is only supported for string fields. Default
         value is None.
        :paramtype search: str
        :return: An iterator like instance of Invoice
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Invoice]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.Invoice]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_invoices_list_by_billing_profile_request(
                    billing_account_name=billing_account_name,
                    billing_profile_name=billing_profile_name,
                    period_start_date=period_start_date,
                    period_end_date=period_end_date,
                    filter=filter,
                    order_by=order_by,
                    top=top,
                    skip=skip,
                    count=count,
                    search=search,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.Invoice],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def get_by_billing_subscription(self, invoice_name: str, **kwargs: Any) -> _models.Invoice:
        """Gets an invoice by subscription ID and invoice ID. The operation is supported for billing
        accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement.

        :param invoice_name: The ID that uniquely identifies an invoice. Required.
        :type invoice_name: str
        :return: Invoice. The Invoice is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.Invoice
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.Invoice] = kwargs.pop("cls", None)

        _request = build_invoices_get_by_billing_subscription_request(
            invoice_name=invoice_name,
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.Invoice, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_billing_subscription(
        self,
        *,
        period_start_date: Optional[datetime.date] = None,
        period_end_date: Optional[datetime.date] = None,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        count: Optional[bool] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.Invoice"]:
        """Lists the invoices for a subscription. The operation is supported for billing accounts with
        agreement type Microsoft Partner Agreement or Microsoft Customer Agreement.

        :keyword period_start_date: The start date of the billing period for which the invoice is
         generated. The date is in MM-DD-YYYY format. Default value is None.
        :paramtype period_start_date: ~datetime.date
        :keyword period_end_date: The end date of the billing period for which the invoice is
         generated. The date is in MM-DD-YYYY format. Default value is None.
        :paramtype period_end_date: ~datetime.date
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :keyword count: The count query option allows clients to request a count of the matching
         resources included with the resources in the response. Default value is None.
        :paramtype count: bool
        :keyword search: The search query option allows clients to request items within a collection
         matching a free-text search expression. search is only supported for string fields. Default
         value is None.
        :paramtype search: str
        :return: An iterator like instance of Invoice
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Invoice]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.Invoice]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_invoices_list_by_billing_subscription_request(
                    subscription_id=self._config.subscription_id,
                    period_start_date=period_start_date,
                    period_end_date=period_end_date,
                    filter=filter,
                    order_by=order_by,
                    top=top,
                    skip=skip,
                    count=count,
                    search=search,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.Invoice],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    async def _download_by_billing_subscription_initial(  # pylint: disable=name-too-long
        self, invoice_name: str, *, document_name: Optional[str] = None, **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_invoices_download_by_billing_subscription_request(
            invoice_name=invoice_name,
            subscription_id=self._config.subscription_id,
            document_name=document_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_download_by_billing_subscription(
        self, invoice_name: str, *, document_name: Optional[str] = None, **kwargs: Any
    ) -> AsyncLROPoller[_models.DocumentDownloadResult]:
        """Gets a URL to download an invoice by billing subscription. The operation is supported for
        billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer
        Agreement.

        :param invoice_name: The ID that uniquely identifies an invoice. Required.
        :type invoice_name: str
        :keyword document_name: The ID that uniquely identifies an invoice document. This ID may be an
         identifier for an invoice PDF, a credit note, or a tax receipt. Default value is None.
        :paramtype document_name: str
        :return: An instance of AsyncLROPoller that returns DocumentDownloadResult. The
         DocumentDownloadResult is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DocumentDownloadResult]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.DocumentDownloadResult] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._download_by_billing_subscription_initial(
                invoice_name=invoice_name,
                document_name=document_name,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.DocumentDownloadResult, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.DocumentDownloadResult].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.DocumentDownloadResult](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace_async
    async def get(self, invoice_name: str, **kwargs: Any) -> _models.Invoice:
        """Gets an invoice by ID. The operation is supported for billing accounts with agreement type
        Microsoft Partner Agreement or Microsoft Customer Agreement.

        :param invoice_name: The ID that uniquely identifies an invoice. Required.
        :type invoice_name: str
        :return: Invoice. The Invoice is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.Invoice
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.Invoice] = kwargs.pop("cls", None)

        _request = build_invoices_get_request(
            invoice_name=invoice_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.Invoice, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    async def _download_documents_by_billing_subscription_initial(  # pylint: disable=name-too-long
        self, parameters: Union[List[_models.DocumentDownloadRequest], List[JSON], IO[bytes]], **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_invoices_download_documents_by_billing_subscription_request(
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_download_documents_by_billing_subscription(  # pylint: disable=name-too-long
        self,
        parameters: List[_models.DocumentDownloadRequest],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.DocumentDownloadResult]:
        """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as
        a zip file. The operation is supported for billing accounts with agreement type Microsoft
        Partner Agreement or Microsoft Customer Agreement.

        :param parameters: A list of download details for individual documents. Required.
        :type parameters: list[~azure.mgmt.billing.models.DocumentDownloadRequest]
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns DocumentDownloadResult. The
         DocumentDownloadResult is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DocumentDownloadResult]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_download_documents_by_billing_subscription(  # pylint: disable=name-too-long
        self, parameters: List[JSON], *, content_type: str = "application/json", **kwargs: Any
    ) -> AsyncLROPoller[_models.DocumentDownloadResult]:
        """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as
        a zip file. The operation is supported for billing accounts with agreement type Microsoft
        Partner Agreement or Microsoft Customer Agreement.

        :param parameters: A list of download details for individual documents. Required.
        :type parameters: list[JSON]
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns DocumentDownloadResult. The
         DocumentDownloadResult is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DocumentDownloadResult]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_download_documents_by_billing_subscription(  # pylint: disable=name-too-long
        self, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any
    ) -> AsyncLROPoller[_models.DocumentDownloadResult]:
        """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as
        a zip file. The operation is supported for billing accounts with agreement type Microsoft
        Partner Agreement or Microsoft Customer Agreement.

        :param parameters: A list of download details for individual documents. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns DocumentDownloadResult. The
         DocumentDownloadResult is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DocumentDownloadResult]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_download_documents_by_billing_subscription(  # pylint: disable=name-too-long
        self, parameters: Union[List[_models.DocumentDownloadRequest], List[JSON], IO[bytes]], **kwargs: Any
    ) -> AsyncLROPoller[_models.DocumentDownloadResult]:
        """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as
        a zip file. The operation is supported for billing accounts with agreement type Microsoft
        Partner Agreement or Microsoft Customer Agreement.

        :param parameters: A list of download details for individual documents. Is one of the following
         types: [DocumentDownloadRequest], [JSON], IO[bytes] Required.
        :type parameters: list[~azure.mgmt.billing.models.DocumentDownloadRequest] or list[JSON] or
         IO[bytes]
        :return: An instance of AsyncLROPoller that returns DocumentDownloadResult. The
         DocumentDownloadResult is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DocumentDownloadResult]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.DocumentDownloadResult] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._download_documents_by_billing_subscription_initial(
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.DocumentDownloadResult, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.DocumentDownloadResult].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.DocumentDownloadResult](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )


class ReservationsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s
        :attr:`reservations` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: BillingManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get_by_reservation_order(
        self,
        billing_account_name: str,
        reservation_order_id: str,
        reservation_id: str,
        *,
        expand: Optional[str] = None,
        **kwargs: Any
    ) -> _models.Reservation:
        """Get Reservation details in the billing account.

        Get specific Reservation details in the billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param reservation_order_id: Order Id of the reservation. Required.
        :type reservation_order_id: str
        :param reservation_id: Id of the reservation item. Required.
        :type reservation_id: str
        :keyword expand: May be used to expand the detail information of some properties. Default value
         is None.
        :paramtype expand: str
        :return: Reservation. The Reservation is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.Reservation
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.Reservation] = kwargs.pop("cls", None)

        _request = build_reservations_get_by_reservation_order_request(
            billing_account_name=billing_account_name,
            reservation_order_id=reservation_order_id,
            reservation_id=reservation_id,
            expand=expand,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.Reservation, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    async def _update_by_billing_account_initial(
        self,
        billing_account_name: str,
        reservation_order_id: str,
        reservation_id: str,
        body: Union[_models.Patch, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(body, (IOBase, bytes)):
            _content = body
        else:
            _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_reservations_update_by_billing_account_request(
            billing_account_name=billing_account_name,
            reservation_order_id=reservation_order_id,
            reservation_id=reservation_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_update_by_billing_account(
        self,
        billing_account_name: str,
        reservation_order_id: str,
        reservation_id: str,
        body: _models.Patch,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.Reservation]:
        """Update reservation by billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param reservation_order_id: Order Id of the reservation. Required.
        :type reservation_order_id: str
        :param reservation_id: Id of the reservation item. Required.
        :type reservation_id: str
        :param body: Request body for patching a reservation. Required.
        :type body: ~azure.mgmt.billing.models.Patch
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns Reservation. The Reservation is compatible
         with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.Reservation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_update_by_billing_account(
        self,
        billing_account_name: str,
        reservation_order_id: str,
        reservation_id: str,
        body: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.Reservation]:
        """Update reservation by billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param reservation_order_id: Order Id of the reservation. Required.
        :type reservation_order_id: str
        :param reservation_id: Id of the reservation item. Required.
        :type reservation_id: str
        :param body: Request body for patching a reservation. Required.
        :type body: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns Reservation. The Reservation is compatible
         with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.Reservation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_update_by_billing_account(
        self,
        billing_account_name: str,
        reservation_order_id: str,
        reservation_id: str,
        body: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.Reservation]:
        """Update reservation by billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param reservation_order_id: Order Id of the reservation. Required.
        :type reservation_order_id: str
        :param reservation_id: Id of the reservation item. Required.
        :type reservation_id: str
        :param body: Request body for patching a reservation. Required.
        :type body: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns Reservation. The Reservation is compatible
         with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.Reservation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_update_by_billing_account(
        self,
        billing_account_name: str,
        reservation_order_id: str,
        reservation_id: str,
        body: Union[_models.Patch, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.Reservation]:
        """Update reservation by billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param reservation_order_id: Order Id of the reservation. Required.
        :type reservation_order_id: str
        :param reservation_id: Id of the reservation item. Required.
        :type reservation_id: str
        :param body: Request body for patching a reservation. Is one of the following types: Patch,
         JSON, IO[bytes] Required.
        :type body: ~azure.mgmt.billing.models.Patch or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns Reservation. The Reservation is compatible
         with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.Reservation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.Reservation] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._update_by_billing_account_initial(
                billing_account_name=billing_account_name,
                reservation_order_id=reservation_order_id,
                reservation_id=reservation_id,
                body=body,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.Reservation, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.Reservation].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.Reservation](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace
    def list_by_reservation_order(
        self, billing_account_name: str, reservation_order_id: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.Reservation"]:
        """Get Reservations in a given reservation Order in the billing account.

        List Reservations within a single ReservationOrder in the billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param reservation_order_id: Order Id of the reservation. Required.
        :type reservation_order_id: str
        :return: An iterator like instance of Reservation
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Reservation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.Reservation]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_reservations_list_by_reservation_order_request(
                    billing_account_name=billing_account_name,
                    reservation_order_id=reservation_order_id,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.Reservation],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_by_billing_account(
        self,
        billing_account_name: str,
        *,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        skiptoken: Optional[float] = None,
        refresh_summary: Optional[str] = None,
        selected_state: Optional[str] = None,
        take: Optional[float] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.Reservation"]:
        """Lists the reservations in the billing account and the roll up counts of reservations group by
        provisioning states.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword skiptoken: The number of reservations to skip from the list before returning results.
         Default value is None.
        :paramtype skiptoken: float
        :keyword refresh_summary: To indicate whether to refresh the roll up counts of the reservations
         group by provisioning states. Default value is None.
        :paramtype refresh_summary: str
        :keyword selected_state: The selected provisioning state. Default value is None.
        :paramtype selected_state: str
        :keyword take: The number of reservations to return in API response. Default value is None.
        :paramtype take: float
        :return: An iterator like instance of Reservation
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Reservation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.Reservation]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_reservations_list_by_billing_account_request(
                    billing_account_name=billing_account_name,
                    filter=filter,
                    order_by=order_by,
                    skiptoken=skiptoken,
                    refresh_summary=refresh_summary,
                    selected_state=selected_state,
                    take=take,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.Reservation],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_by_billing_profile(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        *,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        skiptoken: Optional[float] = None,
        refresh_summary: Optional[str] = None,
        selected_state: Optional[str] = None,
        take: Optional[float] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.Reservation"]:
        """Lists the reservations for a billing profile and the roll up counts of reservations group by
        provisioning state.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword skiptoken: The number of reservations to skip from the list before returning results.
         Default value is None.
        :paramtype skiptoken: float
        :keyword refresh_summary: To indicate whether to refresh the roll up counts of the reservations
         group by provisioning states. Default value is None.
        :paramtype refresh_summary: str
        :keyword selected_state: The selected provisioning state. Default value is None.
        :paramtype selected_state: str
        :keyword take: The number of reservations to return in API response. Default value is None.
        :paramtype take: float
        :return: An iterator like instance of Reservation
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Reservation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.Reservation]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_reservations_list_by_billing_profile_request(
                    billing_account_name=billing_account_name,
                    billing_profile_name=billing_profile_name,
                    filter=filter,
                    order_by=order_by,
                    skiptoken=skiptoken,
                    refresh_summary=refresh_summary,
                    selected_state=selected_state,
                    take=take,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.Reservation],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class BillingAccountsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s
        :attr:`billing_accounts` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: BillingManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(self, billing_account_name: str, **kwargs: Any) -> _models.BillingAccount:
        """Gets a billing account by its ID.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :return: BillingAccount. The BillingAccount is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.BillingAccount
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.BillingAccount] = kwargs.pop("cls", None)

        _request = build_billing_accounts_get_request(
            billing_account_name=billing_account_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.BillingAccount, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    async def _update_initial(
        self, billing_account_name: str, parameters: Union[_models.BillingAccountPatch, JSON, IO[bytes]], **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_billing_accounts_update_request(
            billing_account_name=billing_account_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_update(
        self,
        billing_account_name: str,
        parameters: _models.BillingAccountPatch,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingAccount]:
        """Updates the properties of a billing account. Currently, displayName and address can be updated
        for billing accounts with agreement type Microsoft Customer Agreement. Currently address and
        notification email address can be updated for billing accounts with agreement type Microsoft
        Online Services Agreement. Currently, purchase order number can be edited for billing accounts
        with agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param parameters: A billing account. Required.
        :type parameters: ~azure.mgmt.billing.models.BillingAccountPatch
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingAccount. The BillingAccount is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingAccount]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_update(
        self, billing_account_name: str, parameters: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingAccount]:
        """Updates the properties of a billing account. Currently, displayName and address can be updated
        for billing accounts with agreement type Microsoft Customer Agreement. Currently address and
        notification email address can be updated for billing accounts with agreement type Microsoft
        Online Services Agreement. Currently, purchase order number can be edited for billing accounts
        with agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param parameters: A billing account. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingAccount. The BillingAccount is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingAccount]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_update(
        self, billing_account_name: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingAccount]:
        """Updates the properties of a billing account. Currently, displayName and address can be updated
        for billing accounts with agreement type Microsoft Customer Agreement. Currently address and
        notification email address can be updated for billing accounts with agreement type Microsoft
        Online Services Agreement. Currently, purchase order number can be edited for billing accounts
        with agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param parameters: A billing account. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingAccount. The BillingAccount is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingAccount]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_update(
        self, billing_account_name: str, parameters: Union[_models.BillingAccountPatch, JSON, IO[bytes]], **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingAccount]:
        """Updates the properties of a billing account. Currently, displayName and address can be updated
        for billing accounts with agreement type Microsoft Customer Agreement. Currently address and
        notification email address can be updated for billing accounts with agreement type Microsoft
        Online Services Agreement. Currently, purchase order number can be edited for billing accounts
        with agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param parameters: A billing account. Is one of the following types: BillingAccountPatch, JSON,
         IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.BillingAccountPatch or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns BillingAccount. The BillingAccount is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingAccount]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.BillingAccount] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._update_initial(
                billing_account_name=billing_account_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.BillingAccount, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.BillingAccount].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.BillingAccount](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace
    def list(  # pylint: disable=too-many-locals
        self,
        *,
        include_all: bool = False,
        include_all_without_billing_profiles: bool = False,
        include_deleted: bool = False,
        include_pending_agreement: bool = False,
        include_resellee: bool = False,
        legal_owner_tid: Optional[str] = None,
        legal_owner_oid: Optional[str] = None,
        filter: Optional[str] = None,
        expand: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingAccount"]:
        """Lists the billing accounts that a user has access to.

        :keyword include_all: When true, results will include Billing Accounts that the user does not
         have a direct role assignment on if the user has one of the following AAD roles: Global
         Administrator, Global Reader, Billing Administrator. Default value is False.
        :paramtype include_all: bool
        :keyword include_all_without_billing_profiles: When true, results will include Billing Accounts
         that are not fully created if the user has one of the following AAD roles: Global
         Administrator, Global Reader, Billing Administrator. Default value is False.
        :paramtype include_all_without_billing_profiles: bool
        :keyword include_deleted: When true, results will include any billing accounts in a deleted
         state. Default value is False.
        :paramtype include_deleted: bool
        :keyword include_pending_agreement: Includes billing accounts with agreement pending signature
         that the user has access to. Default value is False.
        :paramtype include_pending_agreement: bool
        :keyword include_resellee: Includes the customer's billing account of Microsoft Partner
         Agreement that the user has access to. Default value is False.
        :paramtype include_resellee: bool
        :keyword legal_owner_tid: Must be combined with legalOwnerOID, results will only include
         Billing Accounts for whom is legally responsible for the Billing Accounts. Optional. Default
         value is None.
        :paramtype legal_owner_tid: str
        :keyword legal_owner_oid: Must be combined with legalOwnerTID, results will only include
         Billing Accounts for whom is legally responsible for the Billing Accounts. Optional. Default
         value is None.
        :paramtype legal_owner_oid: str
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword expand: Expand is allowed for SoldTo and EnrollmentDetails/PONumber. Default value is
         None.
        :paramtype expand: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :keyword search: The search query option allows clients to request items within a collection
         matching a free-text search expression. search is only supported for string fields. Default
         value is None.
        :paramtype search: str
        :return: An iterator like instance of BillingAccount
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingAccount]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingAccount]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_accounts_list_request(
                    include_all=include_all,
                    include_all_without_billing_profiles=include_all_without_billing_profiles,
                    include_deleted=include_deleted,
                    include_pending_agreement=include_pending_agreement,
                    include_resellee=include_resellee,
                    legal_owner_tid=legal_owner_tid,
                    legal_owner_oid=legal_owner_oid,
                    filter=filter,
                    expand=expand,
                    top=top,
                    skip=skip,
                    search=search,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingAccount],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    async def _add_payment_terms_initial(
        self,
        billing_account_name: str,
        parameters: Union[List[_models.PaymentTerm], List[JSON], IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_billing_accounts_add_payment_terms_request(
            billing_account_name=billing_account_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_add_payment_terms(
        self,
        billing_account_name: str,
        parameters: List[_models.PaymentTerm],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingAccount]:
        """Adds payment terms to all the billing profiles under the billing account. Currently, payment
        terms can be added only on billing accounts that have Agreement Type as 'Microsoft Customer
        Agreement' and AccountType as 'Enterprise'. This action needs pre-authorization and only Field
        Sellers are authorized to add the payment terms and is not a self-serve action.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param parameters: The properties of payment term. Required.
        :type parameters: list[~azure.mgmt.billing.models.PaymentTerm]
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingAccount. The BillingAccount is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingAccount]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_add_payment_terms(
        self,
        billing_account_name: str,
        parameters: List[JSON],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingAccount]:
        """Adds payment terms to all the billing profiles under the billing account. Currently, payment
        terms can be added only on billing accounts that have Agreement Type as 'Microsoft Customer
        Agreement' and AccountType as 'Enterprise'. This action needs pre-authorization and only Field
        Sellers are authorized to add the payment terms and is not a self-serve action.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param parameters: The properties of payment term. Required.
        :type parameters: list[JSON]
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingAccount. The BillingAccount is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingAccount]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_add_payment_terms(
        self, billing_account_name: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingAccount]:
        """Adds payment terms to all the billing profiles under the billing account. Currently, payment
        terms can be added only on billing accounts that have Agreement Type as 'Microsoft Customer
        Agreement' and AccountType as 'Enterprise'. This action needs pre-authorization and only Field
        Sellers are authorized to add the payment terms and is not a self-serve action.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param parameters: The properties of payment term. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingAccount. The BillingAccount is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingAccount]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_add_payment_terms(
        self,
        billing_account_name: str,
        parameters: Union[List[_models.PaymentTerm], List[JSON], IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingAccount]:
        """Adds payment terms to all the billing profiles under the billing account. Currently, payment
        terms can be added only on billing accounts that have Agreement Type as 'Microsoft Customer
        Agreement' and AccountType as 'Enterprise'. This action needs pre-authorization and only Field
        Sellers are authorized to add the payment terms and is not a self-serve action.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param parameters: The properties of payment term. Is one of the following types:
         [PaymentTerm], [JSON], IO[bytes] Required.
        :type parameters: list[~azure.mgmt.billing.models.PaymentTerm] or list[JSON] or IO[bytes]
        :return: An instance of AsyncLROPoller that returns BillingAccount. The BillingAccount is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingAccount]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.BillingAccount] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._add_payment_terms_initial(
                billing_account_name=billing_account_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.BillingAccount, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.BillingAccount].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.BillingAccount](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _cancel_payment_terms_initial(
        self, billing_account_name: str, parameters: datetime.datetime, **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: str = kwargs.pop("content_type", _headers.pop("content-type", "application/json"))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True, format="rfc3339")  # type: ignore

        _request = build_billing_accounts_cancel_payment_terms_request(
            billing_account_name=billing_account_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_cancel_payment_terms(
        self, billing_account_name: str, parameters: datetime.datetime, **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingAccount]:
        """Cancels all the payment terms on billing account that falls after the cancellation date in the
        request. Currently, cancel payment terms is only served by admin actions and is not a
        self-serve action.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param parameters: Date after which any payment terms that needs to be cancelled. Required.
        :type parameters: ~datetime.datetime
        :return: An instance of AsyncLROPoller that returns BillingAccount. The BillingAccount is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingAccount]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: str = kwargs.pop("content_type", _headers.pop("content-type", "application/json"))
        cls: ClsType[_models.BillingAccount] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._cancel_payment_terms_initial(
                billing_account_name=billing_account_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.BillingAccount, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.BillingAccount].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.BillingAccount](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace_async
    async def confirm_transition(self, billing_account_name: str, **kwargs: Any) -> _models.TransitionDetails:
        """Gets the transition details for a billing account that has transitioned from agreement type
        Microsoft Online Services Program to agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :return: TransitionDetails. The TransitionDetails is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.TransitionDetails
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.TransitionDetails] = kwargs.pop("cls", None)

        _request = build_billing_accounts_confirm_transition_request(
            billing_account_name=billing_account_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TransitionDetails, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_invoice_sections_by_create_subscription_permission(  # pylint: disable=name-too-long
        self, billing_account_name: str, *, filter: Optional[str] = None, **kwargs: Any
    ) -> AsyncItemPaged["_models.InvoiceSectionWithCreateSubPermission"]:
        """Lists the invoice sections for which the user has permission to create Azure subscriptions. The
        operation is supported only for billing accounts with agreement type Microsoft Customer
        Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :return: An iterator like instance of InvoiceSectionWithCreateSubPermission
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.InvoiceSectionWithCreateSubPermission]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.InvoiceSectionWithCreateSubPermission]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_accounts_list_invoice_sections_by_create_subscription_permission_request(
                    billing_account_name=billing_account_name,
                    filter=filter,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.InvoiceSectionWithCreateSubPermission],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @overload
    async def validate_payment_terms(
        self,
        billing_account_name: str,
        parameters: List[_models.PaymentTerm],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.PaymentTermsEligibilityResult:
        """Validates payment terms on a billing account with agreement type 'Microsoft Customer Agreement'
        and account type 'Enterprise'.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param parameters: The properties of payment term. Required.
        :type parameters: list[~azure.mgmt.billing.models.PaymentTerm]
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: PaymentTermsEligibilityResult. The PaymentTermsEligibilityResult is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.billing.models.PaymentTermsEligibilityResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def validate_payment_terms(
        self,
        billing_account_name: str,
        parameters: List[JSON],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.PaymentTermsEligibilityResult:
        """Validates payment terms on a billing account with agreement type 'Microsoft Customer Agreement'
        and account type 'Enterprise'.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param parameters: The properties of payment term. Required.
        :type parameters: list[JSON]
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: PaymentTermsEligibilityResult. The PaymentTermsEligibilityResult is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.billing.models.PaymentTermsEligibilityResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def validate_payment_terms(
        self, billing_account_name: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.PaymentTermsEligibilityResult:
        """Validates payment terms on a billing account with agreement type 'Microsoft Customer Agreement'
        and account type 'Enterprise'.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param parameters: The properties of payment term. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: PaymentTermsEligibilityResult. The PaymentTermsEligibilityResult is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.billing.models.PaymentTermsEligibilityResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def validate_payment_terms(
        self,
        billing_account_name: str,
        parameters: Union[List[_models.PaymentTerm], List[JSON], IO[bytes]],
        **kwargs: Any
    ) -> _models.PaymentTermsEligibilityResult:
        """Validates payment terms on a billing account with agreement type 'Microsoft Customer Agreement'
        and account type 'Enterprise'.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param parameters: The properties of payment term. Is one of the following types:
         [PaymentTerm], [JSON], IO[bytes] Required.
        :type parameters: list[~azure.mgmt.billing.models.PaymentTerm] or list[JSON] or IO[bytes]
        :return: PaymentTermsEligibilityResult. The PaymentTermsEligibilityResult is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.billing.models.PaymentTermsEligibilityResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.PaymentTermsEligibilityResult] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_billing_accounts_validate_payment_terms_request(
            billing_account_name=billing_account_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PaymentTermsEligibilityResult, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class AssociatedTenantsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s
        :attr:`associated_tenants` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: BillingManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, billing_account_name: str, associated_tenant_name: str, **kwargs: Any
    ) -> _models.AssociatedTenant:
        """Gets an associated tenant by ID.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param associated_tenant_name: The ID that uniquely identifies a tenant. Required.
        :type associated_tenant_name: str
        :return: AssociatedTenant. The AssociatedTenant is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.AssociatedTenant
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.AssociatedTenant] = kwargs.pop("cls", None)

        _request = build_associated_tenants_get_request(
            billing_account_name=billing_account_name,
            associated_tenant_name=associated_tenant_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.AssociatedTenant, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    async def _create_or_update_initial(
        self,
        billing_account_name: str,
        associated_tenant_name: str,
        parameters: Union[_models.AssociatedTenant, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_associated_tenants_create_or_update_request(
            billing_account_name=billing_account_name,
            associated_tenant_name=associated_tenant_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 201:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_or_update(
        self,
        billing_account_name: str,
        associated_tenant_name: str,
        parameters: _models.AssociatedTenant,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.AssociatedTenant]:
        """Create or update an associated tenant for the billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param associated_tenant_name: The ID that uniquely identifies a tenant. Required.
        :type associated_tenant_name: str
        :param parameters: An associated tenant. Required.
        :type parameters: ~azure.mgmt.billing.models.AssociatedTenant
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns AssociatedTenant. The AssociatedTenant is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.AssociatedTenant]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        billing_account_name: str,
        associated_tenant_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.AssociatedTenant]:
        """Create or update an associated tenant for the billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param associated_tenant_name: The ID that uniquely identifies a tenant. Required.
        :type associated_tenant_name: str
        :param parameters: An associated tenant. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns AssociatedTenant. The AssociatedTenant is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.AssociatedTenant]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        billing_account_name: str,
        associated_tenant_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.AssociatedTenant]:
        """Create or update an associated tenant for the billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param associated_tenant_name: The ID that uniquely identifies a tenant. Required.
        :type associated_tenant_name: str
        :param parameters: An associated tenant. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns AssociatedTenant. The AssociatedTenant is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.AssociatedTenant]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_or_update(
        self,
        billing_account_name: str,
        associated_tenant_name: str,
        parameters: Union[_models.AssociatedTenant, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.AssociatedTenant]:
        """Create or update an associated tenant for the billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param associated_tenant_name: The ID that uniquely identifies a tenant. Required.
        :type associated_tenant_name: str
        :param parameters: An associated tenant. Is one of the following types: AssociatedTenant, JSON,
         IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.AssociatedTenant or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns AssociatedTenant. The AssociatedTenant is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.AssociatedTenant]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.AssociatedTenant] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_or_update_initial(
                billing_account_name=billing_account_name,
                associated_tenant_name=associated_tenant_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.AssociatedTenant, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.AssociatedTenant].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.AssociatedTenant](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _delete_initial(
        self, billing_account_name: str, associated_tenant_name: str, **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_associated_tenants_delete_request(
            billing_account_name=billing_account_name,
            associated_tenant_name=associated_tenant_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [202, 204]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_delete(
        self, billing_account_name: str, associated_tenant_name: str, **kwargs: Any
    ) -> AsyncLROPoller[None]:
        """Deletes an associated tenant for a billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param associated_tenant_name: The ID that uniquely identifies a tenant. Required.
        :type associated_tenant_name: str
        :return: An instance of AsyncLROPoller that returns None
        :rtype: ~azure.core.polling.AsyncLROPoller[None]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._delete_initial(
                billing_account_name=billing_account_name,
                associated_tenant_name=associated_tenant_name,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):  # pylint: disable=inconsistent-return-statements
            if cls:
                return cls(pipeline_response, None, {})  # type: ignore

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[None].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method)  # type: ignore

    @distributed_trace
    def list_by_billing_account(
        self,
        billing_account_name: str,
        *,
        include_revoked: bool = False,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        count: Optional[bool] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.AssociatedTenant"]:
        """Lists the associated tenants that can collaborate with the billing account on commerce
        activities like viewing and downloading invoices, managing payments, making purchases, and
        managing or provisioning licenses.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :keyword include_revoked: Can be used to get revoked associated tenants. Default value is
         False.
        :paramtype include_revoked: bool
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :keyword count: The count query option allows clients to request a count of the matching
         resources included with the resources in the response. Default value is None.
        :paramtype count: bool
        :keyword search: The search query option allows clients to request items within a collection
         matching a free-text search expression. search is only supported for string fields. Default
         value is None.
        :paramtype search: str
        :return: An iterator like instance of AssociatedTenant
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.AssociatedTenant]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.AssociatedTenant]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_associated_tenants_list_by_billing_account_request(
                    billing_account_name=billing_account_name,
                    include_revoked=include_revoked,
                    filter=filter,
                    order_by=order_by,
                    top=top,
                    skip=skip,
                    count=count,
                    search=search,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.AssociatedTenant],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class AvailableBalancesOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s
        :attr:`available_balances` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: BillingManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get_by_billing_account(self, billing_account_name: str, **kwargs: Any) -> _models.AvailableBalance:
        """The Available Credit or Payment on Account Balance for a billing account. The credit balance
        can be used to settle due or past due invoices and is supported for billing accounts with
        agreement type Microsoft Customer Agreement. The payment on account balance is supported for
        billing accounts with agreement type Microsoft Customer Agreement or Microsoft Online Services
        Program.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :return: AvailableBalance. The AvailableBalance is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.AvailableBalance
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.AvailableBalance] = kwargs.pop("cls", None)

        _request = build_available_balances_get_by_billing_account_request(
            billing_account_name=billing_account_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.AvailableBalance, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_by_billing_profile(
        self, billing_account_name: str, billing_profile_name: str, **kwargs: Any
    ) -> _models.AvailableBalance:
        """The Available Credit or Payment on Account Balance for a billing profile. The credit balance
        can be used to settle due or past due invoices and is supported for billing accounts with
        agreement type Microsoft Customer Agreement. The payment on account balance is supported for
        billing accounts with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :return: AvailableBalance. The AvailableBalance is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.AvailableBalance
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.AvailableBalance] = kwargs.pop("cls", None)

        _request = build_available_balances_get_by_billing_profile_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.AvailableBalance, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class ProductsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s
        :attr:`products` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: BillingManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(self, billing_account_name: str, product_name: str, **kwargs: Any) -> _models.Product:
        """Gets a product by ID. The operation is supported only for billing accounts with agreement type
        Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param product_name: The ID that uniquely identifies a product. Required.
        :type product_name: str
        :return: Product. The Product is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.Product
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.Product] = kwargs.pop("cls", None)

        _request = build_products_get_request(
            billing_account_name=billing_account_name,
            product_name=product_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.Product, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        billing_account_name: str,
        product_name: str,
        parameters: _models.ProductPatch,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.Product:
        """Updates the properties of a Product. Currently, auto renew can be updated. The operation is
        supported only for billing accounts with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param product_name: The ID that uniquely identifies a product. Required.
        :type product_name: str
        :param parameters: A product. Required.
        :type parameters: ~azure.mgmt.billing.models.ProductPatch
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: Product. The Product is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.Product
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        billing_account_name: str,
        product_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.Product:
        """Updates the properties of a Product. Currently, auto renew can be updated. The operation is
        supported only for billing accounts with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param product_name: The ID that uniquely identifies a product. Required.
        :type product_name: str
        :param parameters: A product. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: Product. The Product is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.Product
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        billing_account_name: str,
        product_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.Product:
        """Updates the properties of a Product. Currently, auto renew can be updated. The operation is
        supported only for billing accounts with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param product_name: The ID that uniquely identifies a product. Required.
        :type product_name: str
        :param parameters: A product. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: Product. The Product is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.Product
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        billing_account_name: str,
        product_name: str,
        parameters: Union[_models.ProductPatch, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.Product:
        """Updates the properties of a Product. Currently, auto renew can be updated. The operation is
        supported only for billing accounts with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param product_name: The ID that uniquely identifies a product. Required.
        :type product_name: str
        :param parameters: A product. Is one of the following types: ProductPatch, JSON, IO[bytes]
         Required.
        :type parameters: ~azure.mgmt.billing.models.ProductPatch or JSON or IO[bytes]
        :return: Product. The Product is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.Product
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.Product] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_products_update_request(
            billing_account_name=billing_account_name,
            product_name=product_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.Product, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_billing_account(
        self,
        billing_account_name: str,
        *,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        count: Optional[bool] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.Product"]:
        """Lists the products for a billing account. These don't include products billed based on usage.
        The operation is supported for billing accounts with agreement type Microsoft Customer
        Agreement or Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :keyword count: The count query option allows clients to request a count of the matching
         resources included with the resources in the response. Default value is None.
        :paramtype count: bool
        :keyword search: The search query option allows clients to request items within a collection
         matching a free-text search expression. search is only supported for string fields. Default
         value is None.
        :paramtype search: str
        :return: An iterator like instance of Product
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Product]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.Product]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_products_list_by_billing_account_request(
                    billing_account_name=billing_account_name,
                    filter=filter,
                    order_by=order_by,
                    top=top,
                    skip=skip,
                    count=count,
                    search=search,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.Product],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    async def _move_initial(
        self,
        billing_account_name: str,
        product_name: str,
        parameters: Union[_models.MoveProductRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_products_move_request(
            billing_account_name=billing_account_name,
            product_name=product_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_move(
        self,
        billing_account_name: str,
        product_name: str,
        parameters: _models.MoveProductRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.Product]:
        """Moves a product's charges to a new invoice section. The new invoice section must belong to the
        same billing profile as the existing invoice section. This operation is supported only for
        products that are purchased with a recurring charge and for billing accounts with agreement
        type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param product_name: The ID that uniquely identifies a product. Required.
        :type product_name: str
        :param parameters: The properties of the product to initiate a transfer. Required.
        :type parameters: ~azure.mgmt.billing.models.MoveProductRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns Product. The Product is compatible with
         MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.Product]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_move(
        self,
        billing_account_name: str,
        product_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.Product]:
        """Moves a product's charges to a new invoice section. The new invoice section must belong to the
        same billing profile as the existing invoice section. This operation is supported only for
        products that are purchased with a recurring charge and for billing accounts with agreement
        type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param product_name: The ID that uniquely identifies a product. Required.
        :type product_name: str
        :param parameters: The properties of the product to initiate a transfer. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns Product. The Product is compatible with
         MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.Product]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_move(
        self,
        billing_account_name: str,
        product_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.Product]:
        """Moves a product's charges to a new invoice section. The new invoice section must belong to the
        same billing profile as the existing invoice section. This operation is supported only for
        products that are purchased with a recurring charge and for billing accounts with agreement
        type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param product_name: The ID that uniquely identifies a product. Required.
        :type product_name: str
        :param parameters: The properties of the product to initiate a transfer. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns Product. The Product is compatible with
         MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.Product]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_move(
        self,
        billing_account_name: str,
        product_name: str,
        parameters: Union[_models.MoveProductRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.Product]:
        """Moves a product's charges to a new invoice section. The new invoice section must belong to the
        same billing profile as the existing invoice section. This operation is supported only for
        products that are purchased with a recurring charge and for billing accounts with agreement
        type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param product_name: The ID that uniquely identifies a product. Required.
        :type product_name: str
        :param parameters: The properties of the product to initiate a transfer. Is one of the
         following types: MoveProductRequest, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.MoveProductRequest or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns Product. The Product is compatible with
         MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.Product]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.Product] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._move_initial(
                billing_account_name=billing_account_name,
                product_name=product_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.Product, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.Product].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.Product](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @overload
    async def validate_move_eligibility(
        self,
        billing_account_name: str,
        product_name: str,
        parameters: _models.MoveProductRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.MoveProductEligibilityResult:
        """Validates if a product's charges can be moved to a new invoice section. This operation is
        supported only for products that are purchased with a recurring charge and for billing accounts
        with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param product_name: The ID that uniquely identifies a product. Required.
        :type product_name: str
        :param parameters: The properties of the product to initiate a transfer. Required.
        :type parameters: ~azure.mgmt.billing.models.MoveProductRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: MoveProductEligibilityResult. The MoveProductEligibilityResult is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.billing.models.MoveProductEligibilityResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def validate_move_eligibility(
        self,
        billing_account_name: str,
        product_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.MoveProductEligibilityResult:
        """Validates if a product's charges can be moved to a new invoice section. This operation is
        supported only for products that are purchased with a recurring charge and for billing accounts
        with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param product_name: The ID that uniquely identifies a product. Required.
        :type product_name: str
        :param parameters: The properties of the product to initiate a transfer. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: MoveProductEligibilityResult. The MoveProductEligibilityResult is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.billing.models.MoveProductEligibilityResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def validate_move_eligibility(
        self,
        billing_account_name: str,
        product_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.MoveProductEligibilityResult:
        """Validates if a product's charges can be moved to a new invoice section. This operation is
        supported only for products that are purchased with a recurring charge and for billing accounts
        with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param product_name: The ID that uniquely identifies a product. Required.
        :type product_name: str
        :param parameters: The properties of the product to initiate a transfer. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: MoveProductEligibilityResult. The MoveProductEligibilityResult is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.billing.models.MoveProductEligibilityResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def validate_move_eligibility(
        self,
        billing_account_name: str,
        product_name: str,
        parameters: Union[_models.MoveProductRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.MoveProductEligibilityResult:
        """Validates if a product's charges can be moved to a new invoice section. This operation is
        supported only for products that are purchased with a recurring charge and for billing accounts
        with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param product_name: The ID that uniquely identifies a product. Required.
        :type product_name: str
        :param parameters: The properties of the product to initiate a transfer. Is one of the
         following types: MoveProductRequest, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.MoveProductRequest or JSON or IO[bytes]
        :return: MoveProductEligibilityResult. The MoveProductEligibilityResult is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.billing.models.MoveProductEligibilityResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.MoveProductEligibilityResult] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_products_validate_move_eligibility_request(
            billing_account_name=billing_account_name,
            product_name=product_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.MoveProductEligibilityResult, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_billing_profile(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        *,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        count: Optional[bool] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.Product"]:
        """Lists the products for a billing profile. These don't include products billed based on usage.
        The operation is supported for billing accounts with agreement type Microsoft Customer
        Agreement or Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :keyword count: The count query option allows clients to request a count of the matching
         resources included with the resources in the response. Default value is None.
        :paramtype count: bool
        :keyword search: The search query option allows clients to request items within a collection
         matching a free-text search expression. search is only supported for string fields. Default
         value is None.
        :paramtype search: str
        :return: An iterator like instance of Product
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Product]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.Product]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_products_list_by_billing_profile_request(
                    billing_account_name=billing_account_name,
                    billing_profile_name=billing_profile_name,
                    filter=filter,
                    order_by=order_by,
                    top=top,
                    skip=skip,
                    count=count,
                    search=search,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.Product],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_by_customer(
        self,
        billing_account_name: str,
        customer_name: str,
        *,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        count: Optional[bool] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.Product"]:
        """Lists the products for a customer. These don't include products billed based on usage.The
        operation is supported only for billing accounts with agreement type Microsoft Partner
        Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :keyword count: The count query option allows clients to request a count of the matching
         resources included with the resources in the response. Default value is None.
        :paramtype count: bool
        :keyword search: The search query option allows clients to request items within a collection
         matching a free-text search expression. search is only supported for string fields. Default
         value is None.
        :paramtype search: str
        :return: An iterator like instance of Product
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Product]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.Product]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_products_list_by_customer_request(
                    billing_account_name=billing_account_name,
                    customer_name=customer_name,
                    filter=filter,
                    order_by=order_by,
                    top=top,
                    skip=skip,
                    count=count,
                    search=search,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.Product],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_by_invoice_section(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        invoice_section_name: str,
        *,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        count: Optional[bool] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.Product"]:
        """Lists the products for an invoice section. These don't include products billed based on usage.
        The operation is supported only for billing accounts with agreement type Microsoft Customer
        Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :keyword count: The count query option allows clients to request a count of the matching
         resources included with the resources in the response. Default value is None.
        :paramtype count: bool
        :keyword search: The search query option allows clients to request items within a collection
         matching a free-text search expression. search is only supported for string fields. Default
         value is None.
        :paramtype search: str
        :return: An iterator like instance of Product
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Product]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.Product]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_products_list_by_invoice_section_request(
                    billing_account_name=billing_account_name,
                    billing_profile_name=billing_profile_name,
                    invoice_section_name=invoice_section_name,
                    filter=filter,
                    order_by=order_by,
                    top=top,
                    skip=skip,
                    count=count,
                    search=search,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.Product],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class BillingProfilesOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s
        :attr:`billing_profiles` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: BillingManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(self, billing_account_name: str, billing_profile_name: str, **kwargs: Any) -> _models.BillingProfile:
        """Gets a billing profile by its ID. The operation is supported for billing accounts with
        agreement type Microsoft Customer Agreement and Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :return: BillingProfile. The BillingProfile is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.BillingProfile
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.BillingProfile] = kwargs.pop("cls", None)

        _request = build_billing_profiles_get_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.BillingProfile, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    async def _create_or_update_initial(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        parameters: Union[_models.BillingProfile, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_billing_profiles_create_or_update_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 201:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_or_update(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        parameters: _models.BillingProfile,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingProfile]:
        """Creates or updates a billing profile. The operation is supported for billing accounts with
        agreement type Microsoft Customer Agreement and Microsoft Partner Agreement. If you are a MCA
        Individual (Pay-as-you-go) customer, then please use the Azure portal experience to create the
        billing profile.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param parameters: A billing profile. Required.
        :type parameters: ~azure.mgmt.billing.models.BillingProfile
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingProfile. The BillingProfile is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingProfile]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingProfile]:
        """Creates or updates a billing profile. The operation is supported for billing accounts with
        agreement type Microsoft Customer Agreement and Microsoft Partner Agreement. If you are a MCA
        Individual (Pay-as-you-go) customer, then please use the Azure portal experience to create the
        billing profile.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param parameters: A billing profile. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingProfile. The BillingProfile is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingProfile]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingProfile]:
        """Creates or updates a billing profile. The operation is supported for billing accounts with
        agreement type Microsoft Customer Agreement and Microsoft Partner Agreement. If you are a MCA
        Individual (Pay-as-you-go) customer, then please use the Azure portal experience to create the
        billing profile.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param parameters: A billing profile. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingProfile. The BillingProfile is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingProfile]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_or_update(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        parameters: Union[_models.BillingProfile, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingProfile]:
        """Creates or updates a billing profile. The operation is supported for billing accounts with
        agreement type Microsoft Customer Agreement and Microsoft Partner Agreement. If you are a MCA
        Individual (Pay-as-you-go) customer, then please use the Azure portal experience to create the
        billing profile.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param parameters: A billing profile. Is one of the following types: BillingProfile, JSON,
         IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.BillingProfile or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns BillingProfile. The BillingProfile is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingProfile]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.BillingProfile] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_or_update_initial(
                billing_account_name=billing_account_name,
                billing_profile_name=billing_profile_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.BillingProfile, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.BillingProfile].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.BillingProfile](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _delete_initial(
        self, billing_account_name: str, billing_profile_name: str, **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_billing_profiles_delete_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [202, 204]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_delete(
        self, billing_account_name: str, billing_profile_name: str, **kwargs: Any
    ) -> AsyncLROPoller[None]:
        """Deletes a billing profile. The operation is supported for billing accounts with agreement type
        Microsoft Customer Agreement and Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :return: An instance of AsyncLROPoller that returns None
        :rtype: ~azure.core.polling.AsyncLROPoller[None]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._delete_initial(
                billing_account_name=billing_account_name,
                billing_profile_name=billing_profile_name,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):  # pylint: disable=inconsistent-return-statements
            if cls:
                return cls(pipeline_response, None, {})  # type: ignore

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[None].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method)  # type: ignore

    @distributed_trace
    def list_by_billing_account(
        self,
        billing_account_name: str,
        *,
        include_deleted: bool = False,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        count: Optional[bool] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingProfile"]:
        """Lists the billing profiles that a user has access to. The operation is supported for billing
        accounts with agreement of type Microsoft Customer Agreement and Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :keyword include_deleted: Can be used to get deleted billing profiles. Default value is False.
        :paramtype include_deleted: bool
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :keyword count: The count query option allows clients to request a count of the matching
         resources included with the resources in the response. Default value is None.
        :paramtype count: bool
        :keyword search: The search query option allows clients to request items within a collection
         matching a free-text search expression. search is only supported for string fields. Default
         value is None.
        :paramtype search: str
        :return: An iterator like instance of BillingProfile
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingProfile]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingProfile]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_profiles_list_by_billing_account_request(
                    billing_account_name=billing_account_name,
                    include_deleted=include_deleted,
                    filter=filter,
                    order_by=order_by,
                    top=top,
                    skip=skip,
                    count=count,
                    search=search,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingProfile],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def validate_delete_eligibility(
        self, billing_account_name: str, billing_profile_name: str, **kwargs: Any
    ) -> _models.DeleteBillingProfileEligibilityResult:
        """Validates if the billing profile can be deleted. The operation is supported for billing
        accounts with agreement type Microsoft Customer Agreement and Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :return: DeleteBillingProfileEligibilityResult. The DeleteBillingProfileEligibilityResult is
         compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.DeleteBillingProfileEligibilityResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.DeleteBillingProfileEligibilityResult] = kwargs.pop("cls", None)

        _request = build_billing_profiles_validate_delete_eligibility_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.DeleteBillingProfileEligibilityResult, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class BillingSubscriptionsOperations:  # pylint: disable=too-many-public-methods
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s
        :attr:`billing_subscriptions` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: BillingManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get_by_billing_profile(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        billing_subscription_name: str,
        *,
        expand: Optional[str] = None,
        **kwargs: Any
    ) -> _models.BillingSubscription:
        """Gets a subscription by its billing profile and ID. The operation is supported for billing
        accounts with agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param billing_subscription_name: The ID that uniquely identifies a subscription. Required.
        :type billing_subscription_name: str
        :keyword expand: Can be used to expand ``Reseller``, ``ConsumptionCostCenter``,
         ``LastMonthCharges`` and ``MonthToDateCharges``. Default value is None.
        :paramtype expand: str
        :return: BillingSubscription. The BillingSubscription is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.BillingSubscription
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.BillingSubscription] = kwargs.pop("cls", None)

        _request = build_billing_subscriptions_get_by_billing_profile_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            billing_subscription_name=billing_subscription_name,
            expand=expand,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.BillingSubscription, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_billing_profile(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        *,
        include_deleted: bool = False,
        expand: Optional[str] = None,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        count: Optional[bool] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingSubscription"]:
        """Lists the subscriptions that are billed to a billing profile. The operation is supported for
        billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner
        Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :keyword include_deleted: Can be used to get deleted billing subscriptions. Default value is
         False.
        :paramtype include_deleted: bool
        :keyword expand: Can be used to expand ``Reseller``, ``ConsumptionCostCenter``,
         ``LastMonthCharges`` and ``MonthToDateCharges``. Default value is None.
        :paramtype expand: str
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :keyword count: The count query option allows clients to request a count of the matching
         resources included with the resources in the response. Default value is None.
        :paramtype count: bool
        :keyword search: The search query option allows clients to request items within a collection
         matching a free-text search expression. search is only supported for string fields. Default
         value is None.
        :paramtype search: str
        :return: An iterator like instance of BillingSubscription
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingSubscription]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingSubscription]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_subscriptions_list_by_billing_profile_request(
                    billing_account_name=billing_account_name,
                    billing_profile_name=billing_profile_name,
                    include_deleted=include_deleted,
                    expand=expand,
                    filter=filter,
                    order_by=order_by,
                    top=top,
                    skip=skip,
                    count=count,
                    search=search,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingSubscription],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def get(
        self, billing_account_name: str, billing_subscription_name: str, *, expand: Optional[str] = None, **kwargs: Any
    ) -> _models.BillingSubscription:
        """Gets a subscription by its ID. The operation is supported for billing accounts with agreement
        type Microsoft Customer Agreement,  Microsoft Partner Agreement, and Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_subscription_name: The ID that uniquely identifies a subscription. Required.
        :type billing_subscription_name: str
        :keyword expand: Can be used to expand ``Reseller``, ``ConsumptionCostCenter``,
         ``LastMonthCharges`` and ``MonthToDateCharges``. Default value is None.
        :paramtype expand: str
        :return: BillingSubscription. The BillingSubscription is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.BillingSubscription
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.BillingSubscription] = kwargs.pop("cls", None)

        _request = build_billing_subscriptions_get_request(
            billing_account_name=billing_account_name,
            billing_subscription_name=billing_subscription_name,
            expand=expand,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.BillingSubscription, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    async def _update_initial(
        self,
        billing_account_name: str,
        billing_subscription_name: str,
        parameters: Union[_models.BillingSubscriptionPatch, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_billing_subscriptions_update_request(
            billing_account_name=billing_account_name,
            billing_subscription_name=billing_subscription_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_update(
        self,
        billing_account_name: str,
        billing_subscription_name: str,
        parameters: _models.BillingSubscriptionPatch,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingSubscription]:
        """Updates the properties of a billing subscription.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_subscription_name: The ID that uniquely identifies a subscription. Required.
        :type billing_subscription_name: str
        :param parameters: The billing properties of a subscription. Required.
        :type parameters: ~azure.mgmt.billing.models.BillingSubscriptionPatch
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingSubscription. The
         BillingSubscription is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingSubscription]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_update(
        self,
        billing_account_name: str,
        billing_subscription_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingSubscription]:
        """Updates the properties of a billing subscription.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_subscription_name: The ID that uniquely identifies a subscription. Required.
        :type billing_subscription_name: str
        :param parameters: The billing properties of a subscription. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingSubscription. The
         BillingSubscription is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingSubscription]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_update(
        self,
        billing_account_name: str,
        billing_subscription_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingSubscription]:
        """Updates the properties of a billing subscription.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_subscription_name: The ID that uniquely identifies a subscription. Required.
        :type billing_subscription_name: str
        :param parameters: The billing properties of a subscription. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingSubscription. The
         BillingSubscription is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingSubscription]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_update(
        self,
        billing_account_name: str,
        billing_subscription_name: str,
        parameters: Union[_models.BillingSubscriptionPatch, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingSubscription]:
        """Updates the properties of a billing subscription.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_subscription_name: The ID that uniquely identifies a subscription. Required.
        :type billing_subscription_name: str
        :param parameters: The billing properties of a subscription. Is one of the following types:
         BillingSubscriptionPatch, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.BillingSubscriptionPatch or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns BillingSubscription. The
         BillingSubscription is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingSubscription]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.BillingSubscription] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._update_initial(
                billing_account_name=billing_account_name,
                billing_subscription_name=billing_subscription_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.BillingSubscription, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.BillingSubscription].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.BillingSubscription](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _delete_initial(
        self, billing_account_name: str, billing_subscription_name: str, **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_billing_subscriptions_delete_request(
            billing_account_name=billing_account_name,
            billing_subscription_name=billing_subscription_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [202, 204]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_delete(
        self, billing_account_name: str, billing_subscription_name: str, **kwargs: Any
    ) -> AsyncLROPoller[None]:
        """Cancels a billing subscription. This operation is supported only for billing accounts of type
        Microsoft Partner Agreement or Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_subscription_name: The ID that uniquely identifies a subscription. Required.
        :type billing_subscription_name: str
        :return: An instance of AsyncLROPoller that returns None
        :rtype: ~azure.core.polling.AsyncLROPoller[None]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._delete_initial(
                billing_account_name=billing_account_name,
                billing_subscription_name=billing_subscription_name,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):  # pylint: disable=inconsistent-return-statements
            if cls:
                return cls(pipeline_response, None, {})  # type: ignore

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[None].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method)  # type: ignore

    @distributed_trace
    def list_by_billing_account(
        self,
        billing_account_name: str,
        *,
        include_deleted: bool = False,
        include_tenant_subscriptions: bool = False,
        include_failed: bool = False,
        expand: Optional[str] = None,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        count: Optional[bool] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingSubscription"]:
        """Lists the subscriptions for a billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :keyword include_deleted: Can be used to get deleted billing subscriptions. Default value is
         False.
        :paramtype include_deleted: bool
        :keyword include_tenant_subscriptions: Can be used to get tenant-owned billing subscriptions.
         This field is only applies to Microsoft Online Services Program billing accounts. Default value
         is False.
        :paramtype include_tenant_subscriptions: bool
        :keyword include_failed: Can be used to get failed billing subscriptions. Default value is
         False.
        :paramtype include_failed: bool
        :keyword expand: Can be used to expand ``Reseller``, ``ConsumptionCostCenter``,
         ``LastMonthCharges`` and ``MonthToDateCharges``. Default value is None.
        :paramtype expand: str
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :keyword count: The count query option allows clients to request a count of the matching
         resources included with the resources in the response. Default value is None.
        :paramtype count: bool
        :keyword search: The search query option allows clients to request items within a collection
         matching a free-text search expression. search is only supported for string fields. Default
         value is None.
        :paramtype search: str
        :return: An iterator like instance of BillingSubscription
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingSubscription]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingSubscription]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_subscriptions_list_by_billing_account_request(
                    billing_account_name=billing_account_name,
                    include_deleted=include_deleted,
                    include_tenant_subscriptions=include_tenant_subscriptions,
                    include_failed=include_failed,
                    expand=expand,
                    filter=filter,
                    order_by=order_by,
                    top=top,
                    skip=skip,
                    count=count,
                    search=search,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingSubscription],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    async def _cancel_initial(
        self,
        billing_account_name: str,
        billing_subscription_name: str,
        parameters: Union[_models.CancelSubscriptionRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_billing_subscriptions_cancel_request(
            billing_account_name=billing_account_name,
            billing_subscription_name=billing_subscription_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
        response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_cancel(
        self,
        billing_account_name: str,
        billing_subscription_name: str,
        parameters: _models.CancelSubscriptionRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[None]:
        """Cancels a usage-based subscription. This operation is supported only for billing accounts of
        type Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_subscription_name: The ID that uniquely identifies a subscription. Required.
        :type billing_subscription_name: str
        :param parameters: Request parameters for cancel customer subscription. Required.
        :type parameters: ~azure.mgmt.billing.models.CancelSubscriptionRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns None
        :rtype: ~azure.core.polling.AsyncLROPoller[None]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_cancel(
        self,
        billing_account_name: str,
        billing_subscription_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[None]:
        """Cancels a usage-based subscription. This operation is supported only for billing accounts of
        type Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_subscription_name: The ID that uniquely identifies a subscription. Required.
        :type billing_subscription_name: str
        :param parameters: Request parameters for cancel customer subscription. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns None
        :rtype: ~azure.core.polling.AsyncLROPoller[None]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_cancel(
        self,
        billing_account_name: str,
        billing_subscription_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[None]:
        """Cancels a usage-based subscription. This operation is supported only for billing accounts of
        type Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_subscription_name: The ID that uniquely identifies a subscription. Required.
        :type billing_subscription_name: str
        :param parameters: Request parameters for cancel customer subscription. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns None
        :rtype: ~azure.core.polling.AsyncLROPoller[None]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_cancel(
        self,
        billing_account_name: str,
        billing_subscription_name: str,
        parameters: Union[_models.CancelSubscriptionRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[None]:
        """Cancels a usage-based subscription. This operation is supported only for billing accounts of
        type Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_subscription_name: The ID that uniquely identifies a subscription. Required.
        :type billing_subscription_name: str
        :param parameters: Request parameters for cancel customer subscription. Is one of the following
         types: CancelSubscriptionRequest, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.CancelSubscriptionRequest or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns None
        :rtype: ~azure.core.polling.AsyncLROPoller[None]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[None] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._cancel_initial(
                billing_account_name=billing_account_name,
                billing_subscription_name=billing_subscription_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):  # pylint: disable=inconsistent-return-statements
            if cls:
                return cls(pipeline_response, None, {})  # type: ignore

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[None].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method)  # type: ignore

    async def _merge_initial(
        self,
        billing_account_name: str,
        billing_subscription_name: str,
        parameters: Union[_models.BillingSubscriptionMergeRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_billing_subscriptions_merge_request(
            billing_account_name=billing_account_name,
            billing_subscription_name=billing_subscription_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_merge(
        self,
        billing_account_name: str,
        billing_subscription_name: str,
        parameters: _models.BillingSubscriptionMergeRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingSubscription]:
        """Merges the billing subscription provided in the request with a target billing subscription.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_subscription_name: The ID that uniquely identifies a subscription. Required.
        :type billing_subscription_name: str
        :param parameters: Request parameters that are provided to merge the two billing subscriptions.
         Required.
        :type parameters: ~azure.mgmt.billing.models.BillingSubscriptionMergeRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingSubscription. The
         BillingSubscription is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingSubscription]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_merge(
        self,
        billing_account_name: str,
        billing_subscription_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingSubscription]:
        """Merges the billing subscription provided in the request with a target billing subscription.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_subscription_name: The ID that uniquely identifies a subscription. Required.
        :type billing_subscription_name: str
        :param parameters: Request parameters that are provided to merge the two billing subscriptions.
         Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingSubscription. The
         BillingSubscription is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingSubscription]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_merge(
        self,
        billing_account_name: str,
        billing_subscription_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingSubscription]:
        """Merges the billing subscription provided in the request with a target billing subscription.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_subscription_name: The ID that uniquely identifies a subscription. Required.
        :type billing_subscription_name: str
        :param parameters: Request parameters that are provided to merge the two billing subscriptions.
         Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingSubscription. The
         BillingSubscription is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingSubscription]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_merge(
        self,
        billing_account_name: str,
        billing_subscription_name: str,
        parameters: Union[_models.BillingSubscriptionMergeRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingSubscription]:
        """Merges the billing subscription provided in the request with a target billing subscription.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_subscription_name: The ID that uniquely identifies a subscription. Required.
        :type billing_subscription_name: str
        :param parameters: Request parameters that are provided to merge the two billing subscriptions.
         Is one of the following types: BillingSubscriptionMergeRequest, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.BillingSubscriptionMergeRequest or JSON or
         IO[bytes]
        :return: An instance of AsyncLROPoller that returns BillingSubscription. The
         BillingSubscription is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingSubscription]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.BillingSubscription] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._merge_initial(
                billing_account_name=billing_account_name,
                billing_subscription_name=billing_subscription_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.BillingSubscription, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.BillingSubscription].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.BillingSubscription](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _move_initial(
        self,
        billing_account_name: str,
        billing_subscription_name: str,
        parameters: Union[_models.MoveBillingSubscriptionRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_billing_subscriptions_move_request(
            billing_account_name=billing_account_name,
            billing_subscription_name=billing_subscription_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_move(
        self,
        billing_account_name: str,
        billing_subscription_name: str,
        parameters: _models.MoveBillingSubscriptionRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingSubscription]:
        """Moves charges for a subscription to a new invoice section. The new invoice section must belong
        to the same billing profile as the existing invoice section. This operation is supported for
        billing accounts with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_subscription_name: The ID that uniquely identifies a subscription. Required.
        :type billing_subscription_name: str
        :param parameters: Request parameters to transfer billing subscription. Required.
        :type parameters: ~azure.mgmt.billing.models.MoveBillingSubscriptionRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingSubscription. The
         BillingSubscription is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingSubscription]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_move(
        self,
        billing_account_name: str,
        billing_subscription_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingSubscription]:
        """Moves charges for a subscription to a new invoice section. The new invoice section must belong
        to the same billing profile as the existing invoice section. This operation is supported for
        billing accounts with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_subscription_name: The ID that uniquely identifies a subscription. Required.
        :type billing_subscription_name: str
        :param parameters: Request parameters to transfer billing subscription. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingSubscription. The
         BillingSubscription is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingSubscription]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_move(
        self,
        billing_account_name: str,
        billing_subscription_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingSubscription]:
        """Moves charges for a subscription to a new invoice section. The new invoice section must belong
        to the same billing profile as the existing invoice section. This operation is supported for
        billing accounts with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_subscription_name: The ID that uniquely identifies a subscription. Required.
        :type billing_subscription_name: str
        :param parameters: Request parameters to transfer billing subscription. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingSubscription. The
         BillingSubscription is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingSubscription]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_move(
        self,
        billing_account_name: str,
        billing_subscription_name: str,
        parameters: Union[_models.MoveBillingSubscriptionRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingSubscription]:
        """Moves charges for a subscription to a new invoice section. The new invoice section must belong
        to the same billing profile as the existing invoice section. This operation is supported for
        billing accounts with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_subscription_name: The ID that uniquely identifies a subscription. Required.
        :type billing_subscription_name: str
        :param parameters: Request parameters to transfer billing subscription. Is one of the following
         types: MoveBillingSubscriptionRequest, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.MoveBillingSubscriptionRequest or JSON or
         IO[bytes]
        :return: An instance of AsyncLROPoller that returns BillingSubscription. The
         BillingSubscription is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingSubscription]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.BillingSubscription] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._move_initial(
                billing_account_name=billing_account_name,
                billing_subscription_name=billing_subscription_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.BillingSubscription, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.BillingSubscription].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.BillingSubscription](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _split_initial(
        self,
        billing_account_name: str,
        billing_subscription_name: str,
        parameters: Union[_models.BillingSubscriptionSplitRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_billing_subscriptions_split_request(
            billing_account_name=billing_account_name,
            billing_subscription_name=billing_subscription_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_split(
        self,
        billing_account_name: str,
        billing_subscription_name: str,
        parameters: _models.BillingSubscriptionSplitRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingSubscription]:
        """Splits a subscription into a new subscription with quantity less than current subscription
        quantity and not equal to 0.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_subscription_name: The ID that uniquely identifies a subscription. Required.
        :type billing_subscription_name: str
        :param parameters: Request parameters that are provided to split the billing subscription.
         Required.
        :type parameters: ~azure.mgmt.billing.models.BillingSubscriptionSplitRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingSubscription. The
         BillingSubscription is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingSubscription]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_split(
        self,
        billing_account_name: str,
        billing_subscription_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingSubscription]:
        """Splits a subscription into a new subscription with quantity less than current subscription
        quantity and not equal to 0.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_subscription_name: The ID that uniquely identifies a subscription. Required.
        :type billing_subscription_name: str
        :param parameters: Request parameters that are provided to split the billing subscription.
         Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingSubscription. The
         BillingSubscription is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingSubscription]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_split(
        self,
        billing_account_name: str,
        billing_subscription_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingSubscription]:
        """Splits a subscription into a new subscription with quantity less than current subscription
        quantity and not equal to 0.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_subscription_name: The ID that uniquely identifies a subscription. Required.
        :type billing_subscription_name: str
        :param parameters: Request parameters that are provided to split the billing subscription.
         Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingSubscription. The
         BillingSubscription is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingSubscription]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_split(
        self,
        billing_account_name: str,
        billing_subscription_name: str,
        parameters: Union[_models.BillingSubscriptionSplitRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingSubscription]:
        """Splits a subscription into a new subscription with quantity less than current subscription
        quantity and not equal to 0.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_subscription_name: The ID that uniquely identifies a subscription. Required.
        :type billing_subscription_name: str
        :param parameters: Request parameters that are provided to split the billing subscription. Is
         one of the following types: BillingSubscriptionSplitRequest, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.BillingSubscriptionSplitRequest or JSON or
         IO[bytes]
        :return: An instance of AsyncLROPoller that returns BillingSubscription. The
         BillingSubscription is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingSubscription]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.BillingSubscription] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._split_initial(
                billing_account_name=billing_account_name,
                billing_subscription_name=billing_subscription_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.BillingSubscription, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.BillingSubscription].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.BillingSubscription](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @overload
    async def validate_move_eligibility(
        self,
        billing_account_name: str,
        billing_subscription_name: str,
        parameters: _models.MoveBillingSubscriptionRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.MoveBillingSubscriptionEligibilityResult:
        """Validates if charges for a subscription can be moved to a new invoice section. This operation
        is supported for billing accounts with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_subscription_name: The ID that uniquely identifies a subscription. Required.
        :type billing_subscription_name: str
        :param parameters: Request parameters to transfer billing subscription. Required.
        :type parameters: ~azure.mgmt.billing.models.MoveBillingSubscriptionRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: MoveBillingSubscriptionEligibilityResult. The MoveBillingSubscriptionEligibilityResult
         is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.MoveBillingSubscriptionEligibilityResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def validate_move_eligibility(
        self,
        billing_account_name: str,
        billing_subscription_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.MoveBillingSubscriptionEligibilityResult:
        """Validates if charges for a subscription can be moved to a new invoice section. This operation
        is supported for billing accounts with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_subscription_name: The ID that uniquely identifies a subscription. Required.
        :type billing_subscription_name: str
        :param parameters: Request parameters to transfer billing subscription. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: MoveBillingSubscriptionEligibilityResult. The MoveBillingSubscriptionEligibilityResult
         is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.MoveBillingSubscriptionEligibilityResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def validate_move_eligibility(
        self,
        billing_account_name: str,
        billing_subscription_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.MoveBillingSubscriptionEligibilityResult:
        """Validates if charges for a subscription can be moved to a new invoice section. This operation
        is supported for billing accounts with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_subscription_name: The ID that uniquely identifies a subscription. Required.
        :type billing_subscription_name: str
        :param parameters: Request parameters to transfer billing subscription. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: MoveBillingSubscriptionEligibilityResult. The MoveBillingSubscriptionEligibilityResult
         is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.MoveBillingSubscriptionEligibilityResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def validate_move_eligibility(
        self,
        billing_account_name: str,
        billing_subscription_name: str,
        parameters: Union[_models.MoveBillingSubscriptionRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.MoveBillingSubscriptionEligibilityResult:
        """Validates if charges for a subscription can be moved to a new invoice section. This operation
        is supported for billing accounts with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_subscription_name: The ID that uniquely identifies a subscription. Required.
        :type billing_subscription_name: str
        :param parameters: Request parameters to transfer billing subscription. Is one of the following
         types: MoveBillingSubscriptionRequest, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.MoveBillingSubscriptionRequest or JSON or
         IO[bytes]
        :return: MoveBillingSubscriptionEligibilityResult. The MoveBillingSubscriptionEligibilityResult
         is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.MoveBillingSubscriptionEligibilityResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.MoveBillingSubscriptionEligibilityResult] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_billing_subscriptions_validate_move_eligibility_request(
            billing_account_name=billing_account_name,
            billing_subscription_name=billing_subscription_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.MoveBillingSubscriptionEligibilityResult, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_customer(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        customer_name: str,
        *,
        include_deleted: bool = False,
        expand: Optional[str] = None,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        count: Optional[bool] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingSubscription"]:
        """Lists the subscriptions for a customer. The operation is supported only for billing accounts
        with agreement type Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :keyword include_deleted: Can be used to get deleted billing subscriptions. Default value is
         False.
        :paramtype include_deleted: bool
        :keyword expand: Can be used to expand ``Reseller``, ``ConsumptionCostCenter``,
         ``LastMonthCharges`` and ``MonthToDateCharges``. Default value is None.
        :paramtype expand: str
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :keyword count: The count query option allows clients to request a count of the matching
         resources included with the resources in the response. Default value is None.
        :paramtype count: bool
        :keyword search: The search query option allows clients to request items within a collection
         matching a free-text search expression. search is only supported for string fields. Default
         value is None.
        :paramtype search: str
        :return: An iterator like instance of BillingSubscription
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingSubscription]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingSubscription]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_subscriptions_list_by_customer_request(
                    billing_account_name=billing_account_name,
                    billing_profile_name=billing_profile_name,
                    customer_name=customer_name,
                    include_deleted=include_deleted,
                    expand=expand,
                    filter=filter,
                    order_by=order_by,
                    top=top,
                    skip=skip,
                    count=count,
                    search=search,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingSubscription],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_by_customer_at_billing_account(
        self,
        billing_account_name: str,
        customer_name: str,
        *,
        include_deleted: bool = False,
        expand: Optional[str] = None,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        count: Optional[bool] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingSubscription"]:
        """Lists the subscriptions for a customer at billing account level. The operation is supported
        only for billing accounts with agreement type Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :keyword include_deleted: Can be used to get deleted billing subscriptions. Default value is
         False.
        :paramtype include_deleted: bool
        :keyword expand: Can be used to expand ``Reseller``, ``ConsumptionCostCenter``,
         ``LastMonthCharges`` and ``MonthToDateCharges``. Default value is None.
        :paramtype expand: str
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :keyword count: The count query option allows clients to request a count of the matching
         resources included with the resources in the response. Default value is None.
        :paramtype count: bool
        :keyword search: The search query option allows clients to request items within a collection
         matching a free-text search expression. search is only supported for string fields. Default
         value is None.
        :paramtype search: str
        :return: An iterator like instance of BillingSubscription
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingSubscription]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingSubscription]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_subscriptions_list_by_customer_at_billing_account_request(
                    billing_account_name=billing_account_name,
                    customer_name=customer_name,
                    include_deleted=include_deleted,
                    expand=expand,
                    filter=filter,
                    order_by=order_by,
                    top=top,
                    skip=skip,
                    count=count,
                    search=search,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingSubscription],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_by_enrollment_account(
        self,
        billing_account_name: str,
        enrollment_account_name: str,
        *,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        count: Optional[bool] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingSubscription"]:
        """Lists the subscriptions for an enrollment account. The operation is supported for billing
        accounts with agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param enrollment_account_name: The name of the enrollment account. Required.
        :type enrollment_account_name: str
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :keyword count: The count query option allows clients to request a count of the matching
         resources included with the resources in the response. Default value is None.
        :paramtype count: bool
        :keyword search: The search query option allows clients to request items within a collection
         matching a free-text search expression. search is only supported for string fields. Default
         value is None.
        :paramtype search: str
        :return: An iterator like instance of BillingSubscription
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingSubscription]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingSubscription]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_subscriptions_list_by_enrollment_account_request(
                    billing_account_name=billing_account_name,
                    enrollment_account_name=enrollment_account_name,
                    filter=filter,
                    order_by=order_by,
                    top=top,
                    skip=skip,
                    count=count,
                    search=search,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingSubscription],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_by_invoice_section(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        invoice_section_name: str,
        *,
        include_deleted: bool = False,
        expand: Optional[str] = None,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        count: Optional[bool] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingSubscription"]:
        """Lists the subscriptions that are billed to an invoice section. The operation is supported only
        for billing accounts with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :keyword include_deleted: Can be used to get deleted billing subscriptions. Default value is
         False.
        :paramtype include_deleted: bool
        :keyword expand: Can be used to expand ``Reseller``, ``ConsumptionCostCenter``,
         ``LastMonthCharges`` and ``MonthToDateCharges``. Default value is None.
        :paramtype expand: str
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :keyword count: The count query option allows clients to request a count of the matching
         resources included with the resources in the response. Default value is None.
        :paramtype count: bool
        :keyword search: The search query option allows clients to request items within a collection
         matching a free-text search expression. search is only supported for string fields. Default
         value is None.
        :paramtype search: str
        :return: An iterator like instance of BillingSubscription
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingSubscription]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingSubscription]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_subscriptions_list_by_invoice_section_request(
                    billing_account_name=billing_account_name,
                    billing_profile_name=billing_profile_name,
                    invoice_section_name=invoice_section_name,
                    include_deleted=include_deleted,
                    expand=expand,
                    filter=filter,
                    order_by=order_by,
                    top=top,
                    skip=skip,
                    count=count,
                    search=search,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingSubscription],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class PoliciesOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s
        :attr:`policies` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: BillingManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get_by_customer_at_billing_account(
        self, billing_account_name: str, customer_name: str, **kwargs: Any
    ) -> _models.CustomerPolicy:
        """Lists the policies for a customer at billing account scope. This operation is supported only
        for billing accounts with agreement type Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :return: CustomerPolicy. The CustomerPolicy is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.CustomerPolicy
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.CustomerPolicy] = kwargs.pop("cls", None)

        _request = build_policies_get_by_customer_at_billing_account_request(
            billing_account_name=billing_account_name,
            customer_name=customer_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.CustomerPolicy, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    async def _create_or_update_by_customer_at_billing_account_initial(  # pylint: disable=name-too-long
        self,
        billing_account_name: str,
        customer_name: str,
        parameters: Union[_models.CustomerPolicy, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_policies_create_or_update_by_customer_at_billing_account_request(
            billing_account_name=billing_account_name,
            customer_name=customer_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 201:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_or_update_by_customer_at_billing_account(  # pylint: disable=name-too-long
        self,
        billing_account_name: str,
        customer_name: str,
        parameters: _models.CustomerPolicy,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.CustomerPolicy]:
        """Updates the policies for a customer at billing account scope. This operation is supported only
        for billing accounts with agreement type Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :param parameters: A policy at customer scope. Required.
        :type parameters: ~azure.mgmt.billing.models.CustomerPolicy
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns CustomerPolicy. The CustomerPolicy is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.CustomerPolicy]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update_by_customer_at_billing_account(  # pylint: disable=name-too-long
        self,
        billing_account_name: str,
        customer_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.CustomerPolicy]:
        """Updates the policies for a customer at billing account scope. This operation is supported only
        for billing accounts with agreement type Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :param parameters: A policy at customer scope. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns CustomerPolicy. The CustomerPolicy is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.CustomerPolicy]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update_by_customer_at_billing_account(  # pylint: disable=name-too-long
        self,
        billing_account_name: str,
        customer_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.CustomerPolicy]:
        """Updates the policies for a customer at billing account scope. This operation is supported only
        for billing accounts with agreement type Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :param parameters: A policy at customer scope. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns CustomerPolicy. The CustomerPolicy is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.CustomerPolicy]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_or_update_by_customer_at_billing_account(  # pylint: disable=name-too-long
        self,
        billing_account_name: str,
        customer_name: str,
        parameters: Union[_models.CustomerPolicy, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.CustomerPolicy]:
        """Updates the policies for a customer at billing account scope. This operation is supported only
        for billing accounts with agreement type Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :param parameters: A policy at customer scope. Is one of the following types: CustomerPolicy,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.CustomerPolicy or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns CustomerPolicy. The CustomerPolicy is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.CustomerPolicy]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.CustomerPolicy] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_or_update_by_customer_at_billing_account_initial(
                billing_account_name=billing_account_name,
                customer_name=customer_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.CustomerPolicy, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.CustomerPolicy].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.CustomerPolicy](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _create_or_update_by_customer_initial(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        customer_name: str,
        parameters: Union[_models.CustomerPolicy, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_policies_create_or_update_by_customer_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            customer_name=customer_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 201:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_or_update_by_customer(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        customer_name: str,
        parameters: _models.CustomerPolicy,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.CustomerPolicy]:
        """Updates the policies for a customer. This operation is supported only for billing accounts with
        agreement type Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :param parameters: A policy at customer scope. Required.
        :type parameters: ~azure.mgmt.billing.models.CustomerPolicy
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns CustomerPolicy. The CustomerPolicy is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.CustomerPolicy]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update_by_customer(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        customer_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.CustomerPolicy]:
        """Updates the policies for a customer. This operation is supported only for billing accounts with
        agreement type Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :param parameters: A policy at customer scope. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns CustomerPolicy. The CustomerPolicy is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.CustomerPolicy]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update_by_customer(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        customer_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.CustomerPolicy]:
        """Updates the policies for a customer. This operation is supported only for billing accounts with
        agreement type Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :param parameters: A policy at customer scope. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns CustomerPolicy. The CustomerPolicy is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.CustomerPolicy]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_or_update_by_customer(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        customer_name: str,
        parameters: Union[_models.CustomerPolicy, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.CustomerPolicy]:
        """Updates the policies for a customer. This operation is supported only for billing accounts with
        agreement type Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :param parameters: A policy at customer scope. Is one of the following types: CustomerPolicy,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.CustomerPolicy or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns CustomerPolicy. The CustomerPolicy is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.CustomerPolicy]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.CustomerPolicy] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_or_update_by_customer_initial(
                billing_account_name=billing_account_name,
                billing_profile_name=billing_profile_name,
                customer_name=customer_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response_headers = {}
            response = pipeline_response.http_response
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

            deserialized = _deserialize(_models.CustomerPolicy, response.json())
            if cls:
                return cls(pipeline_response, deserialized, response_headers)  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.CustomerPolicy].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.CustomerPolicy](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace_async
    async def get_by_customer(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        customer_name: str,
        policy_name: Union[str, _models.ServiceDefinedResourceName],
        **kwargs: Any
    ) -> _models.CustomerPolicy:
        """Lists the policies for a customer. This operation is supported only for billing accounts with
        agreement type Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :param policy_name: Service-defined resource names such as 'default' which are reserved
         resource names. "default" Required.
        :type policy_name: str or ~azure.mgmt.billing.models.ServiceDefinedResourceName
        :return: CustomerPolicy. The CustomerPolicy is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.CustomerPolicy
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.CustomerPolicy] = kwargs.pop("cls", None)

        _request = build_policies_get_by_customer_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            customer_name=customer_name,
            policy_name=policy_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.CustomerPolicy, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_by_billing_profile(
        self, billing_account_name: str, billing_profile_name: str, **kwargs: Any
    ) -> _models.BillingProfilePolicy:
        """Lists the policies for a billing profile. This operation is supported only for billing accounts
        with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :return: BillingProfilePolicy. The BillingProfilePolicy is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.BillingProfilePolicy
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.BillingProfilePolicy] = kwargs.pop("cls", None)

        _request = build_policies_get_by_billing_profile_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.BillingProfilePolicy, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    async def _create_or_update_by_billing_profile_initial(  # pylint: disable=name-too-long
        self,
        billing_account_name: str,
        billing_profile_name: str,
        parameters: Union[_models.BillingProfilePolicy, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_policies_create_or_update_by_billing_profile_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 201:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_or_update_by_billing_profile(  # pylint: disable=name-too-long
        self,
        billing_account_name: str,
        billing_profile_name: str,
        parameters: _models.BillingProfilePolicy,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingProfilePolicy]:
        """Updates the policies for a billing profile. This operation is supported only for billing
        accounts with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param parameters: A policy at billing profile scope. Required.
        :type parameters: ~azure.mgmt.billing.models.BillingProfilePolicy
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingProfilePolicy. The
         BillingProfilePolicy is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingProfilePolicy]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update_by_billing_profile(  # pylint: disable=name-too-long
        self,
        billing_account_name: str,
        billing_profile_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingProfilePolicy]:
        """Updates the policies for a billing profile. This operation is supported only for billing
        accounts with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param parameters: A policy at billing profile scope. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingProfilePolicy. The
         BillingProfilePolicy is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingProfilePolicy]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update_by_billing_profile(  # pylint: disable=name-too-long
        self,
        billing_account_name: str,
        billing_profile_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingProfilePolicy]:
        """Updates the policies for a billing profile. This operation is supported only for billing
        accounts with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param parameters: A policy at billing profile scope. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingProfilePolicy. The
         BillingProfilePolicy is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingProfilePolicy]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_or_update_by_billing_profile(  # pylint: disable=name-too-long
        self,
        billing_account_name: str,
        billing_profile_name: str,
        parameters: Union[_models.BillingProfilePolicy, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingProfilePolicy]:
        """Updates the policies for a billing profile. This operation is supported only for billing
        accounts with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param parameters: A policy at billing profile scope. Is one of the following types:
         BillingProfilePolicy, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.BillingProfilePolicy or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns BillingProfilePolicy. The
         BillingProfilePolicy is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingProfilePolicy]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.BillingProfilePolicy] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_or_update_by_billing_profile_initial(
                billing_account_name=billing_account_name,
                billing_profile_name=billing_profile_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.BillingProfilePolicy, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.BillingProfilePolicy].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.BillingProfilePolicy](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace_async
    async def get_by_billing_account(self, billing_account_name: str, **kwargs: Any) -> _models.BillingAccountPolicy:
        """Get the policies for a billing account of Enterprise Agreement type.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :return: BillingAccountPolicy. The BillingAccountPolicy is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.BillingAccountPolicy
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.BillingAccountPolicy] = kwargs.pop("cls", None)

        _request = build_policies_get_by_billing_account_request(
            billing_account_name=billing_account_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.BillingAccountPolicy, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    async def _create_or_update_by_billing_account_initial(  # pylint: disable=name-too-long
        self, billing_account_name: str, parameters: Union[_models.BillingAccountPolicy, JSON, IO[bytes]], **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_policies_create_or_update_by_billing_account_request(
            billing_account_name=billing_account_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 201:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_or_update_by_billing_account(  # pylint: disable=name-too-long
        self,
        billing_account_name: str,
        parameters: _models.BillingAccountPolicy,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingAccountPolicy]:
        """Update the policies for a billing account of Enterprise Agreement type.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param parameters: A policy at billing account scope. Required.
        :type parameters: ~azure.mgmt.billing.models.BillingAccountPolicy
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingAccountPolicy. The
         BillingAccountPolicy is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingAccountPolicy]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update_by_billing_account(  # pylint: disable=name-too-long
        self, billing_account_name: str, parameters: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingAccountPolicy]:
        """Update the policies for a billing account of Enterprise Agreement type.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param parameters: A policy at billing account scope. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingAccountPolicy. The
         BillingAccountPolicy is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingAccountPolicy]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update_by_billing_account(  # pylint: disable=name-too-long
        self, billing_account_name: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingAccountPolicy]:
        """Update the policies for a billing account of Enterprise Agreement type.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param parameters: A policy at billing account scope. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingAccountPolicy. The
         BillingAccountPolicy is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingAccountPolicy]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_or_update_by_billing_account(  # pylint: disable=name-too-long
        self, billing_account_name: str, parameters: Union[_models.BillingAccountPolicy, JSON, IO[bytes]], **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingAccountPolicy]:
        """Update the policies for a billing account of Enterprise Agreement type.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param parameters: A policy at billing account scope. Is one of the following types:
         BillingAccountPolicy, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.BillingAccountPolicy or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns BillingAccountPolicy. The
         BillingAccountPolicy is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingAccountPolicy]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.BillingAccountPolicy] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_or_update_by_billing_account_initial(
                billing_account_name=billing_account_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.BillingAccountPolicy, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.BillingAccountPolicy].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.BillingAccountPolicy](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace_async
    async def get_by_subscription(self, **kwargs: Any) -> _models.SubscriptionPolicy:
        """Lists the policies that are managed by the Billing Admin for the defined subscriptions. This is
        supported for Microsoft Online Services Program, Microsoft Customer Agreement and Microsoft
        Partner Agreement.

        :return: SubscriptionPolicy. The SubscriptionPolicy is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.SubscriptionPolicy
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.SubscriptionPolicy] = kwargs.pop("cls", None)

        _request = build_policies_get_by_subscription_request(
            subscription_id=self._config.subscription_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.SubscriptionPolicy, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class CustomersOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s
        :attr:`customers` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: BillingManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, billing_account_name: str, billing_profile_name: str, customer_name: str, **kwargs: Any
    ) -> _models.Customer:
        """Gets a customer by its ID. The operation is supported only for billing accounts with agreement
        type Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :return: Customer. The Customer is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.Customer
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.Customer] = kwargs.pop("cls", None)

        _request = build_customers_get_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            customer_name=customer_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.Customer, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_billing_profile(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        *,
        expand: Optional[str] = None,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        count: Optional[bool] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.Customer"]:
        """Lists the customers that are billed to a billing profile. The operation is supported only for
        billing accounts with agreement type Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :keyword expand: May be used to expand enabledAzurePlans and resellers. Default value is None.
        :paramtype expand: str
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :keyword count: The count query option allows clients to request a count of the matching
         resources included with the resources in the response. Default value is None.
        :paramtype count: bool
        :keyword search: The search query option allows clients to request items within a collection
         matching a free-text search expression. search is only supported for string fields. Default
         value is None.
        :paramtype search: str
        :return: An iterator like instance of Customer
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Customer]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.Customer]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_customers_list_by_billing_profile_request(
                    billing_account_name=billing_account_name,
                    billing_profile_name=billing_profile_name,
                    expand=expand,
                    filter=filter,
                    order_by=order_by,
                    top=top,
                    skip=skip,
                    count=count,
                    search=search,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.Customer],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def get_by_billing_account(
        self, billing_account_name: str, customer_name: str, **kwargs: Any
    ) -> _models.Customer:
        """Gets a customer by its ID at billing account level. The operation is supported only for billing
        accounts with agreement type Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :return: Customer. The Customer is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.Customer
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.Customer] = kwargs.pop("cls", None)

        _request = build_customers_get_by_billing_account_request(
            billing_account_name=billing_account_name,
            customer_name=customer_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.Customer, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_billing_account(
        self,
        billing_account_name: str,
        *,
        expand: Optional[str] = None,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        count: Optional[bool] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.Customer"]:
        """Lists the customers that are billed to a billing account. The operation is supported only for
        billing accounts with agreement type Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :keyword expand: May be used to expand enabledAzurePlans and resellers. Default value is None.
        :paramtype expand: str
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :keyword count: The count query option allows clients to request a count of the matching
         resources included with the resources in the response. Default value is None.
        :paramtype count: bool
        :keyword search: The search query option allows clients to request items within a collection
         matching a free-text search expression. search is only supported for string fields. Default
         value is None.
        :paramtype search: str
        :return: An iterator like instance of Customer
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Customer]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.Customer]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_customers_list_by_billing_account_request(
                    billing_account_name=billing_account_name,
                    expand=expand,
                    filter=filter,
                    order_by=order_by,
                    top=top,
                    skip=skip,
                    count=count,
                    search=search,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.Customer],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class DepartmentsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s
        :attr:`departments` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: BillingManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(self, billing_account_name: str, department_name: str, **kwargs: Any) -> _models.Department:
        """Gets a department by ID. The operation is supported only for billing accounts with agreement
        type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param department_name: The name of the department. Required.
        :type department_name: str
        :return: Department. The Department is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.Department
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.Department] = kwargs.pop("cls", None)

        _request = build_departments_get_request(
            billing_account_name=billing_account_name,
            department_name=department_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.Department, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_billing_account(
        self,
        billing_account_name: str,
        *,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.Department"]:
        """Lists the departments that a user has access to. The operation is supported only for billing
        accounts with agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :keyword search: The search query option allows clients to request items within a collection
         matching a free-text search expression. search is only supported for string fields. Default
         value is None.
        :paramtype search: str
        :return: An iterator like instance of Department
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Department]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.Department]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_departments_list_by_billing_account_request(
                    billing_account_name=billing_account_name,
                    filter=filter,
                    order_by=order_by,
                    top=top,
                    skip=skip,
                    search=search,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.Department],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class EnrollmentAccountsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s
        :attr:`enrollment_accounts` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: BillingManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get_by_department(
        self, billing_account_name: str, department_name: str, enrollment_account_name: str, **kwargs: Any
    ) -> _models.EnrollmentAccount:
        """Gets an enrollment account by department. The operation is supported only for billing accounts
        with agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param department_name: The name of the department. Required.
        :type department_name: str
        :param enrollment_account_name: The name of the enrollment account. Required.
        :type enrollment_account_name: str
        :return: EnrollmentAccount. The EnrollmentAccount is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.EnrollmentAccount
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.EnrollmentAccount] = kwargs.pop("cls", None)

        _request = build_enrollment_accounts_get_by_department_request(
            billing_account_name=billing_account_name,
            department_name=department_name,
            enrollment_account_name=enrollment_account_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.EnrollmentAccount, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_department(
        self,
        billing_account_name: str,
        department_name: str,
        *,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        count: Optional[bool] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.EnrollmentAccount"]:
        """Lists the enrollment accounts for a department. The operation is supported only for billing
        accounts with agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param department_name: The name of the department. Required.
        :type department_name: str
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :keyword count: The count query option allows clients to request a count of the matching
         resources included with the resources in the response. Default value is None.
        :paramtype count: bool
        :keyword search: The search query option allows clients to request items within a collection
         matching a free-text search expression. search is only supported for string fields. Default
         value is None.
        :paramtype search: str
        :return: An iterator like instance of EnrollmentAccount
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.EnrollmentAccount]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.EnrollmentAccount]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_enrollment_accounts_list_by_department_request(
                    billing_account_name=billing_account_name,
                    department_name=department_name,
                    filter=filter,
                    order_by=order_by,
                    top=top,
                    skip=skip,
                    count=count,
                    search=search,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.EnrollmentAccount],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def get(
        self, billing_account_name: str, enrollment_account_name: str, **kwargs: Any
    ) -> _models.EnrollmentAccount:
        """Gets an enrollment account by ID. The operation is supported only for billing accounts with
        agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param enrollment_account_name: The name of the enrollment account. Required.
        :type enrollment_account_name: str
        :return: EnrollmentAccount. The EnrollmentAccount is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.EnrollmentAccount
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.EnrollmentAccount] = kwargs.pop("cls", None)

        _request = build_enrollment_accounts_get_request(
            billing_account_name=billing_account_name,
            enrollment_account_name=enrollment_account_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.EnrollmentAccount, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_billing_account(
        self,
        billing_account_name: str,
        *,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        count: Optional[bool] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.EnrollmentAccount"]:
        """Lists the enrollment accounts for a billing account. The operation is supported only for
        billing accounts with agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :keyword count: The count query option allows clients to request a count of the matching
         resources included with the resources in the response. Default value is None.
        :paramtype count: bool
        :keyword search: The search query option allows clients to request items within a collection
         matching a free-text search expression. search is only supported for string fields. Default
         value is None.
        :paramtype search: str
        :return: An iterator like instance of EnrollmentAccount
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.EnrollmentAccount]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.EnrollmentAccount]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_enrollment_accounts_list_by_billing_account_request(
                    billing_account_name=billing_account_name,
                    filter=filter,
                    order_by=order_by,
                    top=top,
                    skip=skip,
                    count=count,
                    search=search,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.EnrollmentAccount],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class InvoiceSectionsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s
        :attr:`invoice_sections` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: BillingManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any
    ) -> _models.InvoiceSection:
        """Gets an invoice section by its ID. The operation is supported only for billing accounts with
        agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :return: InvoiceSection. The InvoiceSection is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.InvoiceSection
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.InvoiceSection] = kwargs.pop("cls", None)

        _request = build_invoice_sections_get_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            invoice_section_name=invoice_section_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.InvoiceSection, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    async def _create_or_update_initial(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        invoice_section_name: str,
        parameters: Union[_models.InvoiceSection, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_invoice_sections_create_or_update_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            invoice_section_name=invoice_section_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 201:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_or_update(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        invoice_section_name: str,
        parameters: _models.InvoiceSection,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.InvoiceSection]:
        """Creates or updates an invoice section. The operation is supported only for billing accounts
        with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :param parameters: An invoice section. Required.
        :type parameters: ~azure.mgmt.billing.models.InvoiceSection
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns InvoiceSection. The InvoiceSection is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.InvoiceSection]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        invoice_section_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.InvoiceSection]:
        """Creates or updates an invoice section. The operation is supported only for billing accounts
        with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :param parameters: An invoice section. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns InvoiceSection. The InvoiceSection is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.InvoiceSection]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        invoice_section_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.InvoiceSection]:
        """Creates or updates an invoice section. The operation is supported only for billing accounts
        with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :param parameters: An invoice section. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns InvoiceSection. The InvoiceSection is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.InvoiceSection]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_or_update(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        invoice_section_name: str,
        parameters: Union[_models.InvoiceSection, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.InvoiceSection]:
        """Creates or updates an invoice section. The operation is supported only for billing accounts
        with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :param parameters: An invoice section. Is one of the following types: InvoiceSection, JSON,
         IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.InvoiceSection or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns InvoiceSection. The InvoiceSection is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.InvoiceSection]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.InvoiceSection] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_or_update_initial(
                billing_account_name=billing_account_name,
                billing_profile_name=billing_profile_name,
                invoice_section_name=invoice_section_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.InvoiceSection, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.InvoiceSection].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.InvoiceSection](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _delete_initial(
        self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_invoice_sections_delete_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            invoice_section_name=invoice_section_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [202, 204]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_delete(
        self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any
    ) -> AsyncLROPoller[None]:
        """Deletes an invoice section. The operation is supported for billing accounts with agreement type
        Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :return: An instance of AsyncLROPoller that returns None
        :rtype: ~azure.core.polling.AsyncLROPoller[None]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._delete_initial(
                billing_account_name=billing_account_name,
                billing_profile_name=billing_profile_name,
                invoice_section_name=invoice_section_name,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):  # pylint: disable=inconsistent-return-statements
            if cls:
                return cls(pipeline_response, None, {})  # type: ignore

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[None].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method)  # type: ignore

    @distributed_trace
    def list_by_billing_profile(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        *,
        include_deleted: bool = False,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        count: Optional[bool] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.InvoiceSection"]:
        """Lists the invoice sections that a user has access to. The operation is supported only for
        billing accounts with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :keyword include_deleted: Can be used to get deleted invoice sections. Default value is False.
        :paramtype include_deleted: bool
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :keyword count: The count query option allows clients to request a count of the matching
         resources included with the resources in the response. Default value is None.
        :paramtype count: bool
        :keyword search: The search query option allows clients to request items within a collection
         matching a free-text search expression. search is only supported for string fields. Default
         value is None.
        :paramtype search: str
        :return: An iterator like instance of InvoiceSection
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.InvoiceSection]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.InvoiceSection]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_invoice_sections_list_by_billing_profile_request(
                    billing_account_name=billing_account_name,
                    billing_profile_name=billing_profile_name,
                    include_deleted=include_deleted,
                    filter=filter,
                    order_by=order_by,
                    top=top,
                    skip=skip,
                    count=count,
                    search=search,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.InvoiceSection],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def validate_delete_eligibility(
        self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any
    ) -> _models.DeleteInvoiceSectionEligibilityResult:
        """Validates if the invoice section can be deleted. The operation is supported for billing
        accounts with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :return: DeleteInvoiceSectionEligibilityResult. The DeleteInvoiceSectionEligibilityResult is
         compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.DeleteInvoiceSectionEligibilityResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.DeleteInvoiceSectionEligibilityResult] = kwargs.pop("cls", None)

        _request = build_invoice_sections_validate_delete_eligibility_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            invoice_section_name=invoice_section_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.DeleteInvoiceSectionEligibilityResult, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class PaymentMethodsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s
        :attr:`payment_methods` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: BillingManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get_by_billing_account(
        self, billing_account_name: str, payment_method_name: str, **kwargs: Any
    ) -> _models.PaymentMethod:
        """Gets a payment method available for a billing account. The operation is supported only for
        billing accounts with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param payment_method_name: The ID that uniquely identifies a payment method. Required.
        :type payment_method_name: str
        :return: PaymentMethod. The PaymentMethod is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.PaymentMethod
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.PaymentMethod] = kwargs.pop("cls", None)

        _request = build_payment_methods_get_by_billing_account_request(
            billing_account_name=billing_account_name,
            payment_method_name=payment_method_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PaymentMethod, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_billing_account(
        self, billing_account_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.PaymentMethod"]:
        """Lists the payment methods available for a billing account. Along with the payment methods owned
        by the caller, these payment methods can be attached to a billing profile to make payments. The
        operation is supported only for billing accounts with agreement type Microsoft Customer
        Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :return: An iterator like instance of PaymentMethod
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.PaymentMethod]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.PaymentMethod]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_payment_methods_list_by_billing_account_request(
                    billing_account_name=billing_account_name,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.PaymentMethod],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def get_by_billing_profile(
        self, billing_account_name: str, billing_profile_name: str, payment_method_name: str, **kwargs: Any
    ) -> _models.PaymentMethodLink:
        """Gets a payment method linked with a billing profile. The operation is supported only for
        billing accounts with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param payment_method_name: The ID that uniquely identifies a payment method. Required.
        :type payment_method_name: str
        :return: PaymentMethodLink. The PaymentMethodLink is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.PaymentMethodLink
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.PaymentMethodLink] = kwargs.pop("cls", None)

        _request = build_payment_methods_get_by_billing_profile_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            payment_method_name=payment_method_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PaymentMethodLink, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_billing_profile(
        self, billing_account_name: str, billing_profile_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.PaymentMethodLink"]:
        """Lists payment methods attached to a billing profile. The operation is supported only for
        billing accounts with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :return: An iterator like instance of PaymentMethodLink
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.PaymentMethodLink]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.PaymentMethodLink]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_payment_methods_list_by_billing_profile_request(
                    billing_account_name=billing_account_name,
                    billing_profile_name=billing_profile_name,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.PaymentMethodLink],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def get_by_user(self, payment_method_name: str, **kwargs: Any) -> _models.PaymentMethod:
        """Gets a payment method owned by the caller.

        :param payment_method_name: The ID that uniquely identifies a payment method. Required.
        :type payment_method_name: str
        :return: PaymentMethod. The PaymentMethod is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.PaymentMethod
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.PaymentMethod] = kwargs.pop("cls", None)

        _request = build_payment_methods_get_by_user_request(
            payment_method_name=payment_method_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PaymentMethod, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete_by_user(self, payment_method_name: str, **kwargs: Any) -> None:
        """Deletes a payment method owned by the caller.

        :param payment_method_name: The ID that uniquely identifies a payment method. Required.
        :type payment_method_name: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_payment_methods_delete_by_user_request(
            payment_method_name=payment_method_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_user(self, **kwargs: Any) -> AsyncItemPaged["_models.PaymentMethod"]:
        """Lists the payment methods owned by the caller.

        :return: An iterator like instance of PaymentMethod
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.PaymentMethod]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.PaymentMethod]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_payment_methods_list_by_user_request(
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.PaymentMethod],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ReservationOrdersOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s
        :attr:`reservation_orders` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: BillingManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get_by_billing_account(
        self, billing_account_name: str, reservation_order_id: str, *, expand: Optional[str] = None, **kwargs: Any
    ) -> _models.ReservationOrder:
        """Get a specific ReservationOrder in the billing account.

        Get the details of the ReservationOrder in the billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param reservation_order_id: Order Id of the reservation. Required.
        :type reservation_order_id: str
        :keyword expand: May be used to expand the detail information of some properties. Default value
         is None.
        :paramtype expand: str
        :return: ReservationOrder. The ReservationOrder is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.ReservationOrder
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ReservationOrder] = kwargs.pop("cls", None)

        _request = build_reservation_orders_get_by_billing_account_request(
            billing_account_name=billing_account_name,
            reservation_order_id=reservation_order_id,
            expand=expand,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ReservationOrder, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_billing_account(
        self,
        billing_account_name: str,
        *,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        skiptoken: Optional[float] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.ReservationOrder"]:
        """Get all `ReservationOrders in the billing account.

        List all the ReservationOrders in the billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword skiptoken: The number of reservations to skip from the list before returning results.
         Default value is None.
        :paramtype skiptoken: float
        :return: An iterator like instance of ReservationOrder
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.ReservationOrder]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ReservationOrder]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_reservation_orders_list_by_billing_account_request(
                    billing_account_name=billing_account_name,
                    filter=filter,
                    order_by=order_by,
                    skiptoken=skiptoken,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ReservationOrder],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class TransfersOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s
        :attr:`transfers` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: BillingManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        invoice_section_name: str,
        transfer_name: str,
        **kwargs: Any
    ) -> _models.TransferDetails:
        """Gets a transfer request by ID. The operation is supported only for billing accounts with
        agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :param transfer_name: The ID that uniquely identifies a transfer request. Required.
        :type transfer_name: str
        :return: TransferDetails. The TransferDetails is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.TransferDetails
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.TransferDetails] = kwargs.pop("cls", None)

        _request = build_transfers_get_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            invoice_section_name=invoice_section_name,
            transfer_name=transfer_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TransferDetails, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def initiate(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        invoice_section_name: str,
        transfer_name: str,
        parameters: _models.InitiateTransferRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.TransferDetails:
        """Sends a request to a user in another billing account to transfer billing ownership of their
        subscriptions. The operation is supported only for billing accounts with agreement type
        Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :param transfer_name: The ID that uniquely identifies a transfer request. Required.
        :type transfer_name: str
        :param parameters: Request parameters that are provided to the initiate transfer operation.
         Required.
        :type parameters: ~azure.mgmt.billing.models.InitiateTransferRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: TransferDetails. The TransferDetails is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.TransferDetails
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def initiate(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        invoice_section_name: str,
        transfer_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.TransferDetails:
        """Sends a request to a user in another billing account to transfer billing ownership of their
        subscriptions. The operation is supported only for billing accounts with agreement type
        Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :param transfer_name: The ID that uniquely identifies a transfer request. Required.
        :type transfer_name: str
        :param parameters: Request parameters that are provided to the initiate transfer operation.
         Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: TransferDetails. The TransferDetails is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.TransferDetails
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def initiate(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        invoice_section_name: str,
        transfer_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.TransferDetails:
        """Sends a request to a user in another billing account to transfer billing ownership of their
        subscriptions. The operation is supported only for billing accounts with agreement type
        Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :param transfer_name: The ID that uniquely identifies a transfer request. Required.
        :type transfer_name: str
        :param parameters: Request parameters that are provided to the initiate transfer operation.
         Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: TransferDetails. The TransferDetails is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.TransferDetails
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def initiate(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        invoice_section_name: str,
        transfer_name: str,
        parameters: Union[_models.InitiateTransferRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.TransferDetails:
        """Sends a request to a user in another billing account to transfer billing ownership of their
        subscriptions. The operation is supported only for billing accounts with agreement type
        Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :param transfer_name: The ID that uniquely identifies a transfer request. Required.
        :type transfer_name: str
        :param parameters: Request parameters that are provided to the initiate transfer operation. Is
         one of the following types: InitiateTransferRequest, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.InitiateTransferRequest or JSON or IO[bytes]
        :return: TransferDetails. The TransferDetails is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.TransferDetails
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.TransferDetails] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_transfers_initiate_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            invoice_section_name=invoice_section_name,
            transfer_name=transfer_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TransferDetails, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list(
        self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.TransferDetails"]:
        """Lists the transfer requests for an invoice section. The operation is supported only for billing
        accounts with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :return: An iterator like instance of TransferDetails
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.TransferDetails]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.TransferDetails]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_transfers_list_request(
                    billing_account_name=billing_account_name,
                    billing_profile_name=billing_profile_name,
                    invoice_section_name=invoice_section_name,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.TransferDetails],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def cancel(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        invoice_section_name: str,
        transfer_name: str,
        **kwargs: Any
    ) -> _models.TransferDetails:
        """Cancels a transfer request. The operation is supported only for billing accounts with agreement
        type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :param transfer_name: The ID that uniquely identifies a transfer request. Required.
        :type transfer_name: str
        :return: TransferDetails. The TransferDetails is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.TransferDetails
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.TransferDetails] = kwargs.pop("cls", None)

        _request = build_transfers_cancel_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            invoice_section_name=invoice_section_name,
            transfer_name=transfer_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TransferDetails, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class PartnerTransfersOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s
        :attr:`partner_transfers` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: BillingManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        customer_name: str,
        transfer_name: str,
        **kwargs: Any
    ) -> _models.PartnerTransferDetails:
        """Gets a transfer request by ID. The operation is supported only for billing accounts with
        agreement type Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :param transfer_name: The ID that uniquely identifies a transfer request. Required.
        :type transfer_name: str
        :return: PartnerTransferDetails. The PartnerTransferDetails is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.PartnerTransferDetails
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.PartnerTransferDetails] = kwargs.pop("cls", None)

        _request = build_partner_transfers_get_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            customer_name=customer_name,
            transfer_name=transfer_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PartnerTransferDetails, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def initiate(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        customer_name: str,
        transfer_name: str,
        parameters: _models.PartnerInitiateTransferRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.PartnerTransferDetails:
        """Sends a request to a user in a customer's billing account to transfer billing ownership of
        their subscriptions. The operation is supported only for billing accounts with agreement type
        Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :param transfer_name: The ID that uniquely identifies a transfer request. Required.
        :type transfer_name: str
        :param parameters: Request parameters that are provided to the initiate transfer operation.
         Required.
        :type parameters: ~azure.mgmt.billing.models.PartnerInitiateTransferRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: PartnerTransferDetails. The PartnerTransferDetails is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.PartnerTransferDetails
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def initiate(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        customer_name: str,
        transfer_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.PartnerTransferDetails:
        """Sends a request to a user in a customer's billing account to transfer billing ownership of
        their subscriptions. The operation is supported only for billing accounts with agreement type
        Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :param transfer_name: The ID that uniquely identifies a transfer request. Required.
        :type transfer_name: str
        :param parameters: Request parameters that are provided to the initiate transfer operation.
         Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: PartnerTransferDetails. The PartnerTransferDetails is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.PartnerTransferDetails
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def initiate(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        customer_name: str,
        transfer_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.PartnerTransferDetails:
        """Sends a request to a user in a customer's billing account to transfer billing ownership of
        their subscriptions. The operation is supported only for billing accounts with agreement type
        Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :param transfer_name: The ID that uniquely identifies a transfer request. Required.
        :type transfer_name: str
        :param parameters: Request parameters that are provided to the initiate transfer operation.
         Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: PartnerTransferDetails. The PartnerTransferDetails is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.PartnerTransferDetails
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def initiate(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        customer_name: str,
        transfer_name: str,
        parameters: Union[_models.PartnerInitiateTransferRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.PartnerTransferDetails:
        """Sends a request to a user in a customer's billing account to transfer billing ownership of
        their subscriptions. The operation is supported only for billing accounts with agreement type
        Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :param transfer_name: The ID that uniquely identifies a transfer request. Required.
        :type transfer_name: str
        :param parameters: Request parameters that are provided to the initiate transfer operation. Is
         one of the following types: PartnerInitiateTransferRequest, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.PartnerInitiateTransferRequest or JSON or
         IO[bytes]
        :return: PartnerTransferDetails. The PartnerTransferDetails is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.PartnerTransferDetails
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.PartnerTransferDetails] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_partner_transfers_initiate_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            customer_name=customer_name,
            transfer_name=transfer_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PartnerTransferDetails, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list(
        self, billing_account_name: str, billing_profile_name: str, customer_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.PartnerTransferDetails"]:
        """Lists the transfer requests sent to a customer. The operation is supported only for billing
        accounts with agreement type Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :return: An iterator like instance of PartnerTransferDetails
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.PartnerTransferDetails]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.PartnerTransferDetails]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_partner_transfers_list_request(
                    billing_account_name=billing_account_name,
                    billing_profile_name=billing_profile_name,
                    customer_name=customer_name,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.PartnerTransferDetails],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def cancel(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        customer_name: str,
        transfer_name: str,
        **kwargs: Any
    ) -> _models.PartnerTransferDetails:
        """Cancels a transfer request. The operation is supported only for billing accounts with agreement
        type Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :param transfer_name: The ID that uniquely identifies a transfer request. Required.
        :type transfer_name: str
        :return: PartnerTransferDetails. The PartnerTransferDetails is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.PartnerTransferDetails
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.PartnerTransferDetails] = kwargs.pop("cls", None)

        _request = build_partner_transfers_cancel_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            customer_name=customer_name,
            transfer_name=transfer_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.PartnerTransferDetails, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class RecipientTransfersOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s
        :attr:`recipient_transfers` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: BillingManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(self, transfer_name: str, **kwargs: Any) -> _models.RecipientTransferDetails:
        """Gets a transfer request by ID. The caller must be the recipient of the transfer request.

        Gets a transfer request by ID. The caller must be the recipient of the transfer request.

        :param transfer_name: The ID that uniquely identifies a transfer request. Required.
        :type transfer_name: str
        :return: RecipientTransferDetails. The RecipientTransferDetails is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.billing.models.RecipientTransferDetails
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.RecipientTransferDetails] = kwargs.pop("cls", None)

        _request = build_recipient_transfers_get_request(
            transfer_name=transfer_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.RecipientTransferDetails, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list(self, **kwargs: Any) -> AsyncItemPaged["_models.RecipientTransferDetails"]:
        """Lists the transfer requests received by the caller.

        Lists the transfer requests received by the caller.

        :return: An iterator like instance of RecipientTransferDetails
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.RecipientTransferDetails]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.RecipientTransferDetails]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_recipient_transfers_list_request(
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.RecipientTransferDetails],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @overload
    async def accept(
        self,
        transfer_name: str,
        parameters: _models.AcceptTransferRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.RecipientTransferDetails:
        """Accepts a transfer request.

        Accepts a transfer request.

        :param transfer_name: The ID that uniquely identifies a transfer request. Required.
        :type transfer_name: str
        :param parameters: Request parameters that are provided to the accept transfer operation.
         Required.
        :type parameters: ~azure.mgmt.billing.models.AcceptTransferRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: RecipientTransferDetails. The RecipientTransferDetails is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.billing.models.RecipientTransferDetails
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def accept(
        self, transfer_name: str, parameters: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.RecipientTransferDetails:
        """Accepts a transfer request.

        Accepts a transfer request.

        :param transfer_name: The ID that uniquely identifies a transfer request. Required.
        :type transfer_name: str
        :param parameters: Request parameters that are provided to the accept transfer operation.
         Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: RecipientTransferDetails. The RecipientTransferDetails is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.billing.models.RecipientTransferDetails
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def accept(
        self, transfer_name: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.RecipientTransferDetails:
        """Accepts a transfer request.

        Accepts a transfer request.

        :param transfer_name: The ID that uniquely identifies a transfer request. Required.
        :type transfer_name: str
        :param parameters: Request parameters that are provided to the accept transfer operation.
         Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: RecipientTransferDetails. The RecipientTransferDetails is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.billing.models.RecipientTransferDetails
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def accept(
        self, transfer_name: str, parameters: Union[_models.AcceptTransferRequest, JSON, IO[bytes]], **kwargs: Any
    ) -> _models.RecipientTransferDetails:
        """Accepts a transfer request.

        Accepts a transfer request.

        :param transfer_name: The ID that uniquely identifies a transfer request. Required.
        :type transfer_name: str
        :param parameters: Request parameters that are provided to the accept transfer operation. Is
         one of the following types: AcceptTransferRequest, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.AcceptTransferRequest or JSON or IO[bytes]
        :return: RecipientTransferDetails. The RecipientTransferDetails is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.billing.models.RecipientTransferDetails
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.RecipientTransferDetails] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_recipient_transfers_accept_request(
            transfer_name=transfer_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.RecipientTransferDetails, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def validate(
        self,
        transfer_name: str,
        parameters: _models.AcceptTransferRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ValidateTransferListResponse:
        """Validates if a subscription or a reservation can be transferred. Use this operation to validate
        your subscriptions or reservation before using the accept transfer operation.

        Validates if a subscription or a reservation can be transferred. Use this operation to validate
        your subscriptions or reservation before using the accept transfer operation.

        :param transfer_name: The ID that uniquely identifies a transfer request. Required.
        :type transfer_name: str
        :param parameters: Request parameters that are provided to the validate transfer operation.
         Required.
        :type parameters: ~azure.mgmt.billing.models.AcceptTransferRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ValidateTransferListResponse. The ValidateTransferListResponse is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.billing.models.ValidateTransferListResponse
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def validate(
        self, transfer_name: str, parameters: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.ValidateTransferListResponse:
        """Validates if a subscription or a reservation can be transferred. Use this operation to validate
        your subscriptions or reservation before using the accept transfer operation.

        Validates if a subscription or a reservation can be transferred. Use this operation to validate
        your subscriptions or reservation before using the accept transfer operation.

        :param transfer_name: The ID that uniquely identifies a transfer request. Required.
        :type transfer_name: str
        :param parameters: Request parameters that are provided to the validate transfer operation.
         Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ValidateTransferListResponse. The ValidateTransferListResponse is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.billing.models.ValidateTransferListResponse
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def validate(
        self, transfer_name: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.ValidateTransferListResponse:
        """Validates if a subscription or a reservation can be transferred. Use this operation to validate
        your subscriptions or reservation before using the accept transfer operation.

        Validates if a subscription or a reservation can be transferred. Use this operation to validate
        your subscriptions or reservation before using the accept transfer operation.

        :param transfer_name: The ID that uniquely identifies a transfer request. Required.
        :type transfer_name: str
        :param parameters: Request parameters that are provided to the validate transfer operation.
         Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ValidateTransferListResponse. The ValidateTransferListResponse is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.billing.models.ValidateTransferListResponse
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def validate(
        self, transfer_name: str, parameters: Union[_models.AcceptTransferRequest, JSON, IO[bytes]], **kwargs: Any
    ) -> _models.ValidateTransferListResponse:
        """Validates if a subscription or a reservation can be transferred. Use this operation to validate
        your subscriptions or reservation before using the accept transfer operation.

        Validates if a subscription or a reservation can be transferred. Use this operation to validate
        your subscriptions or reservation before using the accept transfer operation.

        :param transfer_name: The ID that uniquely identifies a transfer request. Required.
        :type transfer_name: str
        :param parameters: Request parameters that are provided to the validate transfer operation. Is
         one of the following types: AcceptTransferRequest, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.AcceptTransferRequest or JSON or IO[bytes]
        :return: ValidateTransferListResponse. The ValidateTransferListResponse is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.billing.models.ValidateTransferListResponse
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ValidateTransferListResponse] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_recipient_transfers_validate_request(
            transfer_name=transfer_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ValidateTransferListResponse, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def decline(self, transfer_name: str, **kwargs: Any) -> _models.RecipientTransferDetails:
        """Declines a transfer request.

        Declines a transfer request.

        :param transfer_name: The ID that uniquely identifies a transfer request. Required.
        :type transfer_name: str
        :return: RecipientTransferDetails. The RecipientTransferDetails is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.billing.models.RecipientTransferDetails
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.RecipientTransferDetails] = kwargs.pop("cls", None)

        _request = build_recipient_transfers_decline_request(
            transfer_name=transfer_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.RecipientTransferDetails, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class TransactionsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s
        :attr:`transactions` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: BillingManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list_by_invoice(
        self,
        billing_account_name: str,
        invoice_name: str,
        *,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        count: Optional[bool] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.Transaction"]:
        """Lists the transactions for an invoice. Transactions include purchases, refunds and Azure usage
        charges.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param invoice_name: The ID that uniquely identifies an invoice. Required.
        :type invoice_name: str
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :keyword count: The count query option allows clients to request a count of the matching
         resources included with the resources in the response. Default value is None.
        :paramtype count: bool
        :keyword search: The search query option allows clients to request items within a collection
         matching a free-text search expression. search is only supported for string fields. Default
         value is None.
        :paramtype search: str
        :return: An iterator like instance of Transaction
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Transaction]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.Transaction]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_transactions_list_by_invoice_request(
                    billing_account_name=billing_account_name,
                    invoice_name=invoice_name,
                    filter=filter,
                    order_by=order_by,
                    top=top,
                    skip=skip,
                    count=count,
                    search=search,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.Transaction],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    async def _transactions_download_by_invoice_initial(  # pylint: disable=name-too-long
        self, billing_account_name: str, invoice_name: str, **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_transactions_transactions_download_by_invoice_request(
            billing_account_name=billing_account_name,
            invoice_name=invoice_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_transactions_download_by_invoice(
        self, billing_account_name: str, invoice_name: str, **kwargs: Any
    ) -> AsyncLROPoller[_models.DocumentDownloadResult]:
        """Gets a URL to download the transactions document for an invoice. The operation is supported for
        billing accounts with agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param invoice_name: The ID that uniquely identifies an invoice. Required.
        :type invoice_name: str
        :return: An instance of AsyncLROPoller that returns DocumentDownloadResult. The
         DocumentDownloadResult is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DocumentDownloadResult]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.DocumentDownloadResult] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._transactions_download_by_invoice_initial(
                billing_account_name=billing_account_name,
                invoice_name=invoice_name,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.DocumentDownloadResult, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.DocumentDownloadResult].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.DocumentDownloadResult](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace_async
    async def get_transaction_summary_by_invoice(
        self,
        billing_account_name: str,
        invoice_name: str,
        *,
        filter: Optional[str] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> _models.TransactionSummary:
        """Gets the transaction summary for an invoice. Transactions include purchases, refunds and Azure
        usage charges.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param invoice_name: The ID that uniquely identifies an invoice. Required.
        :type invoice_name: str
        :keyword filter: The filter query option allows clients to filter the line items that are
         aggregated to create the line item summary. Default value is None.
        :paramtype filter: str
        :keyword search: The search query option allows clients to filter the line items that are
         aggregated to create the line item summary. Default value is None.
        :paramtype search: str
        :return: TransactionSummary. The TransactionSummary is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.TransactionSummary
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.TransactionSummary] = kwargs.pop("cls", None)

        _request = build_transactions_get_transaction_summary_by_invoice_request(
            billing_account_name=billing_account_name,
            invoice_name=invoice_name,
            filter=filter,
            search=search,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TransactionSummary, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_billing_profile(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        *,
        period_start_date: datetime.date,
        period_end_date: datetime.date,
        type: Union[str, _models.TransactionType],
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        count: Optional[bool] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.Transaction"]:
        """Lists the billed or unbilled transactions by billing profile name for given start and end date.
        Transactions include purchases, refunds and Azure usage charges. Unbilled transactions are
        listed under pending invoice Id and do not include tax. Tax is added to the amount once an
        invoice is generated.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :keyword period_start_date: The start date to fetch the transactions. The date should be
         specified in MM-DD-YYYY format. Required.
        :paramtype period_start_date: ~datetime.date
        :keyword period_end_date: The end date to fetch the transactions. The date should be specified
         in MM-DD-YYYY format. Required.
        :paramtype period_end_date: ~datetime.date
        :keyword type: The type of transaction. Known values are: "Other", "Billed", and "Unbilled".
         Required.
        :paramtype type: str or ~azure.mgmt.billing.models.TransactionType
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :keyword count: The count query option allows clients to request a count of the matching
         resources included with the resources in the response. Default value is None.
        :paramtype count: bool
        :keyword search: The search query option allows clients to request items within a collection
         matching a free-text search expression. search is only supported for string fields. Default
         value is None.
        :paramtype search: str
        :return: An iterator like instance of Transaction
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Transaction]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.Transaction]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_transactions_list_by_billing_profile_request(
                    billing_account_name=billing_account_name,
                    billing_profile_name=billing_profile_name,
                    period_start_date=period_start_date,
                    period_end_date=period_end_date,
                    type=type,
                    filter=filter,
                    order_by=order_by,
                    top=top,
                    skip=skip,
                    count=count,
                    search=search,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.Transaction],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_by_customer(  # pylint: disable=too-many-locals
        self,
        billing_account_name: str,
        billing_profile_name: str,
        customer_name: str,
        *,
        period_start_date: datetime.date,
        period_end_date: datetime.date,
        type: Union[str, _models.TransactionType],
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        count: Optional[bool] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.Transaction"]:
        """Lists the billed or unbilled transactions by customer id for given start date and end date.
        Transactions include purchases, refunds and Azure usage charges. Unbilled transactions are
        listed under pending invoice Id and do not include tax. Tax is added to the amount once an
        invoice is generated.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :keyword period_start_date: The start date to fetch the transactions. The date should be
         specified in MM-DD-YYYY format. Required.
        :paramtype period_start_date: ~datetime.date
        :keyword period_end_date: The end date to fetch the transactions. The date should be specified
         in MM-DD-YYYY format. Required.
        :paramtype period_end_date: ~datetime.date
        :keyword type: The type of transaction. Known values are: "Other", "Billed", and "Unbilled".
         Required.
        :paramtype type: str or ~azure.mgmt.billing.models.TransactionType
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :keyword count: The count query option allows clients to request a count of the matching
         resources included with the resources in the response. Default value is None.
        :paramtype count: bool
        :keyword search: The search query option allows clients to request items within a collection
         matching a free-text search expression. search is only supported for string fields. Default
         value is None.
        :paramtype search: str
        :return: An iterator like instance of Transaction
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Transaction]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.Transaction]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_transactions_list_by_customer_request(
                    billing_account_name=billing_account_name,
                    billing_profile_name=billing_profile_name,
                    customer_name=customer_name,
                    period_start_date=period_start_date,
                    period_end_date=period_end_date,
                    type=type,
                    filter=filter,
                    order_by=order_by,
                    top=top,
                    skip=skip,
                    count=count,
                    search=search,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.Transaction],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_by_invoice_section(  # pylint: disable=too-many-locals
        self,
        billing_account_name: str,
        billing_profile_name: str,
        invoice_section_name: str,
        *,
        period_start_date: datetime.date,
        period_end_date: datetime.date,
        type: Union[str, _models.TransactionType],
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        count: Optional[bool] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.Transaction"]:
        """Lists the billed or unbilled transactions by invoice section name for given start date and end
        date. Transactions include purchases, refunds and Azure usage charges. Unbilled transactions
        are listed under pending invoice Id and do not include tax. Tax is added to the amount once an
        invoice is generated.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :keyword period_start_date: The start date to fetch the transactions. The date should be
         specified in MM-DD-YYYY format. Required.
        :paramtype period_start_date: ~datetime.date
        :keyword period_end_date: The end date to fetch the transactions. The date should be specified
         in MM-DD-YYYY format. Required.
        :paramtype period_end_date: ~datetime.date
        :keyword type: The type of transaction. Known values are: "Other", "Billed", and "Unbilled".
         Required.
        :paramtype type: str or ~azure.mgmt.billing.models.TransactionType
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :keyword count: The count query option allows clients to request a count of the matching
         resources included with the resources in the response. Default value is None.
        :paramtype count: bool
        :keyword search: The search query option allows clients to request items within a collection
         matching a free-text search expression. search is only supported for string fields. Default
         value is None.
        :paramtype search: str
        :return: An iterator like instance of Transaction
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Transaction]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.Transaction]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_transactions_list_by_invoice_section_request(
                    billing_account_name=billing_account_name,
                    billing_profile_name=billing_profile_name,
                    invoice_section_name=invoice_section_name,
                    period_start_date=period_start_date,
                    period_end_date=period_end_date,
                    type=type,
                    filter=filter,
                    order_by=order_by,
                    top=top,
                    skip=skip,
                    count=count,
                    search=search,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.Transaction],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class BillingPermissionsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s
        :attr:`billing_permissions` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: BillingManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list_by_billing_account(
        self, billing_account_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingPermission"]:
        """Lists the billing permissions the caller has on a billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :return: An iterator like instance of BillingPermission
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingPermission]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingPermission]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_permissions_list_by_billing_account_request(
                    billing_account_name=billing_account_name,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingPermission],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @overload
    async def check_access_by_billing_account(
        self,
        billing_account_name: str,
        parameters: _models.CheckAccessRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> List[_models.CheckAccessResponse]:
        """Provides a list of check access response objects for a billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param parameters: The request object against which access of the caller will be checked.
         Required.
        :type parameters: ~azure.mgmt.billing.models.CheckAccessRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: list of CheckAccessResponse
        :rtype: list[~azure.mgmt.billing.models.CheckAccessResponse]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def check_access_by_billing_account(
        self, billing_account_name: str, parameters: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> List[_models.CheckAccessResponse]:
        """Provides a list of check access response objects for a billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param parameters: The request object against which access of the caller will be checked.
         Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: list of CheckAccessResponse
        :rtype: list[~azure.mgmt.billing.models.CheckAccessResponse]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def check_access_by_billing_account(
        self, billing_account_name: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any
    ) -> List[_models.CheckAccessResponse]:
        """Provides a list of check access response objects for a billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param parameters: The request object against which access of the caller will be checked.
         Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: list of CheckAccessResponse
        :rtype: list[~azure.mgmt.billing.models.CheckAccessResponse]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def check_access_by_billing_account(
        self, billing_account_name: str, parameters: Union[_models.CheckAccessRequest, JSON, IO[bytes]], **kwargs: Any
    ) -> List[_models.CheckAccessResponse]:
        """Provides a list of check access response objects for a billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param parameters: The request object against which access of the caller will be checked. Is
         one of the following types: CheckAccessRequest, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.CheckAccessRequest or JSON or IO[bytes]
        :return: list of CheckAccessResponse
        :rtype: list[~azure.mgmt.billing.models.CheckAccessResponse]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[List[_models.CheckAccessResponse]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_billing_permissions_check_access_by_billing_account_request(
            billing_account_name=billing_account_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(List[_models.CheckAccessResponse], response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_billing_profile(
        self, billing_account_name: str, billing_profile_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingPermission"]:
        """Lists the billing permissions the caller has on a billing profile.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :return: An iterator like instance of BillingPermission
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingPermission]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingPermission]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_permissions_list_by_billing_profile_request(
                    billing_account_name=billing_account_name,
                    billing_profile_name=billing_profile_name,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingPermission],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @overload
    async def check_access_by_billing_profile(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        parameters: _models.CheckAccessRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> List[_models.CheckAccessResponse]:
        """Provides a list of check access response objects for a billing profile.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param parameters: The request object against which access of the caller will be checked.
         Required.
        :type parameters: ~azure.mgmt.billing.models.CheckAccessRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: list of CheckAccessResponse
        :rtype: list[~azure.mgmt.billing.models.CheckAccessResponse]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def check_access_by_billing_profile(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> List[_models.CheckAccessResponse]:
        """Provides a list of check access response objects for a billing profile.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param parameters: The request object against which access of the caller will be checked.
         Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: list of CheckAccessResponse
        :rtype: list[~azure.mgmt.billing.models.CheckAccessResponse]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def check_access_by_billing_profile(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> List[_models.CheckAccessResponse]:
        """Provides a list of check access response objects for a billing profile.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param parameters: The request object against which access of the caller will be checked.
         Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: list of CheckAccessResponse
        :rtype: list[~azure.mgmt.billing.models.CheckAccessResponse]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def check_access_by_billing_profile(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        parameters: Union[_models.CheckAccessRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> List[_models.CheckAccessResponse]:
        """Provides a list of check access response objects for a billing profile.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param parameters: The request object against which access of the caller will be checked. Is
         one of the following types: CheckAccessRequest, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.CheckAccessRequest or JSON or IO[bytes]
        :return: list of CheckAccessResponse
        :rtype: list[~azure.mgmt.billing.models.CheckAccessResponse]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[List[_models.CheckAccessResponse]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_billing_permissions_check_access_by_billing_profile_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(List[_models.CheckAccessResponse], response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_customer(
        self, billing_account_name: str, billing_profile_name: str, customer_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingPermission"]:
        """Lists the billing permissions the caller has for a customer.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :return: An iterator like instance of BillingPermission
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingPermission]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingPermission]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_permissions_list_by_customer_request(
                    billing_account_name=billing_account_name,
                    billing_profile_name=billing_profile_name,
                    customer_name=customer_name,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingPermission],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @overload
    async def check_access_by_customer(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        customer_name: str,
        parameters: _models.CheckAccessRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> List[_models.CheckAccessResponse]:
        """Provides a list of check access response objects for a customer.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :param parameters: The request object against which access of the caller will be checked.
         Required.
        :type parameters: ~azure.mgmt.billing.models.CheckAccessRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: list of CheckAccessResponse
        :rtype: list[~azure.mgmt.billing.models.CheckAccessResponse]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def check_access_by_customer(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        customer_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> List[_models.CheckAccessResponse]:
        """Provides a list of check access response objects for a customer.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :param parameters: The request object against which access of the caller will be checked.
         Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: list of CheckAccessResponse
        :rtype: list[~azure.mgmt.billing.models.CheckAccessResponse]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def check_access_by_customer(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        customer_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> List[_models.CheckAccessResponse]:
        """Provides a list of check access response objects for a customer.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :param parameters: The request object against which access of the caller will be checked.
         Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: list of CheckAccessResponse
        :rtype: list[~azure.mgmt.billing.models.CheckAccessResponse]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def check_access_by_customer(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        customer_name: str,
        parameters: Union[_models.CheckAccessRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> List[_models.CheckAccessResponse]:
        """Provides a list of check access response objects for a customer.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :param parameters: The request object against which access of the caller will be checked. Is
         one of the following types: CheckAccessRequest, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.CheckAccessRequest or JSON or IO[bytes]
        :return: list of CheckAccessResponse
        :rtype: list[~azure.mgmt.billing.models.CheckAccessResponse]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[List[_models.CheckAccessResponse]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_billing_permissions_check_access_by_customer_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            customer_name=customer_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(List[_models.CheckAccessResponse], response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_customer_at_billing_account(
        self, billing_account_name: str, customer_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingPermission"]:
        """Lists the billing permissions the caller has for a customer at billing account level.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :return: An iterator like instance of BillingPermission
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingPermission]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingPermission]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_permissions_list_by_customer_at_billing_account_request(
                    billing_account_name=billing_account_name,
                    customer_name=customer_name,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingPermission],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_by_department(
        self, billing_account_name: str, department_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingPermission"]:
        """Lists the billing permissions the caller has for a department.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param department_name: The name of the department. Required.
        :type department_name: str
        :return: An iterator like instance of BillingPermission
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingPermission]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingPermission]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_permissions_list_by_department_request(
                    billing_account_name=billing_account_name,
                    department_name=department_name,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingPermission],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @overload
    async def check_access_by_department(
        self,
        billing_account_name: str,
        department_name: str,
        parameters: _models.CheckAccessRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> List[_models.CheckAccessResponse]:
        """Provides a list of check access response objects for a department.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param department_name: The name of the department. Required.
        :type department_name: str
        :param parameters: The request object against which access of the caller will be checked.
         Required.
        :type parameters: ~azure.mgmt.billing.models.CheckAccessRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: list of CheckAccessResponse
        :rtype: list[~azure.mgmt.billing.models.CheckAccessResponse]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def check_access_by_department(
        self,
        billing_account_name: str,
        department_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> List[_models.CheckAccessResponse]:
        """Provides a list of check access response objects for a department.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param department_name: The name of the department. Required.
        :type department_name: str
        :param parameters: The request object against which access of the caller will be checked.
         Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: list of CheckAccessResponse
        :rtype: list[~azure.mgmt.billing.models.CheckAccessResponse]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def check_access_by_department(
        self,
        billing_account_name: str,
        department_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> List[_models.CheckAccessResponse]:
        """Provides a list of check access response objects for a department.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param department_name: The name of the department. Required.
        :type department_name: str
        :param parameters: The request object against which access of the caller will be checked.
         Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: list of CheckAccessResponse
        :rtype: list[~azure.mgmt.billing.models.CheckAccessResponse]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def check_access_by_department(
        self,
        billing_account_name: str,
        department_name: str,
        parameters: Union[_models.CheckAccessRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> List[_models.CheckAccessResponse]:
        """Provides a list of check access response objects for a department.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param department_name: The name of the department. Required.
        :type department_name: str
        :param parameters: The request object against which access of the caller will be checked. Is
         one of the following types: CheckAccessRequest, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.CheckAccessRequest or JSON or IO[bytes]
        :return: list of CheckAccessResponse
        :rtype: list[~azure.mgmt.billing.models.CheckAccessResponse]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[List[_models.CheckAccessResponse]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_billing_permissions_check_access_by_department_request(
            billing_account_name=billing_account_name,
            department_name=department_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(List[_models.CheckAccessResponse], response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_enrollment_account(
        self, billing_account_name: str, enrollment_account_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingPermission"]:
        """Lists the billing permissions the caller has for an enrollment account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param enrollment_account_name: The name of the enrollment account. Required.
        :type enrollment_account_name: str
        :return: An iterator like instance of BillingPermission
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingPermission]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingPermission]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_permissions_list_by_enrollment_account_request(
                    billing_account_name=billing_account_name,
                    enrollment_account_name=enrollment_account_name,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingPermission],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @overload
    async def check_access_by_enrollment_account(
        self,
        billing_account_name: str,
        enrollment_account_name: str,
        parameters: _models.CheckAccessRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> List[_models.CheckAccessResponse]:
        """Provides a list of check access response objects for an enrollment account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param enrollment_account_name: The name of the enrollment account. Required.
        :type enrollment_account_name: str
        :param parameters: The request object against which access of the caller will be checked.
         Required.
        :type parameters: ~azure.mgmt.billing.models.CheckAccessRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: list of CheckAccessResponse
        :rtype: list[~azure.mgmt.billing.models.CheckAccessResponse]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def check_access_by_enrollment_account(
        self,
        billing_account_name: str,
        enrollment_account_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> List[_models.CheckAccessResponse]:
        """Provides a list of check access response objects for an enrollment account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param enrollment_account_name: The name of the enrollment account. Required.
        :type enrollment_account_name: str
        :param parameters: The request object against which access of the caller will be checked.
         Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: list of CheckAccessResponse
        :rtype: list[~azure.mgmt.billing.models.CheckAccessResponse]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def check_access_by_enrollment_account(
        self,
        billing_account_name: str,
        enrollment_account_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> List[_models.CheckAccessResponse]:
        """Provides a list of check access response objects for an enrollment account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param enrollment_account_name: The name of the enrollment account. Required.
        :type enrollment_account_name: str
        :param parameters: The request object against which access of the caller will be checked.
         Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: list of CheckAccessResponse
        :rtype: list[~azure.mgmt.billing.models.CheckAccessResponse]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def check_access_by_enrollment_account(
        self,
        billing_account_name: str,
        enrollment_account_name: str,
        parameters: Union[_models.CheckAccessRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> List[_models.CheckAccessResponse]:
        """Provides a list of check access response objects for an enrollment account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param enrollment_account_name: The name of the enrollment account. Required.
        :type enrollment_account_name: str
        :param parameters: The request object against which access of the caller will be checked. Is
         one of the following types: CheckAccessRequest, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.CheckAccessRequest or JSON or IO[bytes]
        :return: list of CheckAccessResponse
        :rtype: list[~azure.mgmt.billing.models.CheckAccessResponse]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[List[_models.CheckAccessResponse]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_billing_permissions_check_access_by_enrollment_account_request(
            billing_account_name=billing_account_name,
            enrollment_account_name=enrollment_account_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(List[_models.CheckAccessResponse], response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_invoice_section(
        self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingPermission"]:
        """Lists the billing permissions the caller has for an invoice section.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :return: An iterator like instance of BillingPermission
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingPermission]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingPermission]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_permissions_list_by_invoice_section_request(
                    billing_account_name=billing_account_name,
                    billing_profile_name=billing_profile_name,
                    invoice_section_name=invoice_section_name,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingPermission],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @overload
    async def check_access_by_invoice_section(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        invoice_section_name: str,
        parameters: _models.CheckAccessRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> List[_models.CheckAccessResponse]:
        """Provides a list of check access response objects for an invoice section.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :param parameters: The request object against which access of the caller will be checked.
         Required.
        :type parameters: ~azure.mgmt.billing.models.CheckAccessRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: list of CheckAccessResponse
        :rtype: list[~azure.mgmt.billing.models.CheckAccessResponse]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def check_access_by_invoice_section(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        invoice_section_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> List[_models.CheckAccessResponse]:
        """Provides a list of check access response objects for an invoice section.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :param parameters: The request object against which access of the caller will be checked.
         Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: list of CheckAccessResponse
        :rtype: list[~azure.mgmt.billing.models.CheckAccessResponse]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def check_access_by_invoice_section(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        invoice_section_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> List[_models.CheckAccessResponse]:
        """Provides a list of check access response objects for an invoice section.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :param parameters: The request object against which access of the caller will be checked.
         Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: list of CheckAccessResponse
        :rtype: list[~azure.mgmt.billing.models.CheckAccessResponse]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def check_access_by_invoice_section(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        invoice_section_name: str,
        parameters: Union[_models.CheckAccessRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> List[_models.CheckAccessResponse]:
        """Provides a list of check access response objects for an invoice section.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :param parameters: The request object against which access of the caller will be checked. Is
         one of the following types: CheckAccessRequest, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.CheckAccessRequest or JSON or IO[bytes]
        :return: list of CheckAccessResponse
        :rtype: list[~azure.mgmt.billing.models.CheckAccessResponse]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[List[_models.CheckAccessResponse]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_billing_permissions_check_access_by_invoice_section_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            invoice_section_name=invoice_section_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(List[_models.CheckAccessResponse], response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class SavingsPlansOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s
        :attr:`savings_plans` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: BillingManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list_by_billing_account(
        self,
        billing_account_name: str,
        *,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        skiptoken: Optional[float] = None,
        take: Optional[float] = None,
        selected_state: Optional[str] = None,
        refresh_summary: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.SavingsPlanModel"]:
        """List savings plans by billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword skiptoken: The number of savings plans to skip from the list before returning results.
         Default value is None.
        :paramtype skiptoken: float
        :keyword take: The number of savings plans to return. Default value is None.
        :paramtype take: float
        :keyword selected_state: The selected provisioning state. Default value is None.
        :paramtype selected_state: str
        :keyword refresh_summary: To indicate whether to refresh the roll up counts of the savings
         plans group by provisioning states. Default value is None.
        :paramtype refresh_summary: str
        :return: An iterator like instance of SavingsPlanModel
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.SavingsPlanModel]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.SavingsPlanModel]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_savings_plans_list_by_billing_account_request(
                    billing_account_name=billing_account_name,
                    filter=filter,
                    order_by=order_by,
                    skiptoken=skiptoken,
                    take=take,
                    selected_state=selected_state,
                    refresh_summary=refresh_summary,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.SavingsPlanModel],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def get_by_billing_account(
        self,
        billing_account_name: str,
        savings_plan_order_id: str,
        savings_plan_id: str,
        *,
        expand: Optional[str] = None,
        **kwargs: Any
    ) -> _models.SavingsPlanModel:
        """Get savings plan by billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param savings_plan_order_id: Order ID of the savings plan. Required.
        :type savings_plan_order_id: str
        :param savings_plan_id: ID of the savings plan. Required.
        :type savings_plan_id: str
        :keyword expand: May be used to expand the planInformation. Default value is None.
        :paramtype expand: str
        :return: SavingsPlanModel. The SavingsPlanModel is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.SavingsPlanModel
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.SavingsPlanModel] = kwargs.pop("cls", None)

        _request = build_savings_plans_get_by_billing_account_request(
            billing_account_name=billing_account_name,
            savings_plan_order_id=savings_plan_order_id,
            savings_plan_id=savings_plan_id,
            expand=expand,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.SavingsPlanModel, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    async def _update_by_billing_account_initial(
        self,
        billing_account_name: str,
        savings_plan_order_id: str,
        savings_plan_id: str,
        body: Union[_models.SavingsPlanUpdateRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(body, (IOBase, bytes)):
            _content = body
        else:
            _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_savings_plans_update_by_billing_account_request(
            billing_account_name=billing_account_name,
            savings_plan_order_id=savings_plan_order_id,
            savings_plan_id=savings_plan_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_update_by_billing_account(
        self,
        billing_account_name: str,
        savings_plan_order_id: str,
        savings_plan_id: str,
        body: _models.SavingsPlanUpdateRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.SavingsPlanModel]:
        """Update savings plan by billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param savings_plan_order_id: Order ID of the savings plan. Required.
        :type savings_plan_order_id: str
        :param savings_plan_id: ID of the savings plan. Required.
        :type savings_plan_id: str
        :param body: Request body for patching a savings plan order alias. Required.
        :type body: ~azure.mgmt.billing.models.SavingsPlanUpdateRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns SavingsPlanModel. The SavingsPlanModel is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.SavingsPlanModel]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_update_by_billing_account(
        self,
        billing_account_name: str,
        savings_plan_order_id: str,
        savings_plan_id: str,
        body: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.SavingsPlanModel]:
        """Update savings plan by billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param savings_plan_order_id: Order ID of the savings plan. Required.
        :type savings_plan_order_id: str
        :param savings_plan_id: ID of the savings plan. Required.
        :type savings_plan_id: str
        :param body: Request body for patching a savings plan order alias. Required.
        :type body: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns SavingsPlanModel. The SavingsPlanModel is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.SavingsPlanModel]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_update_by_billing_account(
        self,
        billing_account_name: str,
        savings_plan_order_id: str,
        savings_plan_id: str,
        body: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.SavingsPlanModel]:
        """Update savings plan by billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param savings_plan_order_id: Order ID of the savings plan. Required.
        :type savings_plan_order_id: str
        :param savings_plan_id: ID of the savings plan. Required.
        :type savings_plan_id: str
        :param body: Request body for patching a savings plan order alias. Required.
        :type body: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns SavingsPlanModel. The SavingsPlanModel is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.SavingsPlanModel]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_update_by_billing_account(
        self,
        billing_account_name: str,
        savings_plan_order_id: str,
        savings_plan_id: str,
        body: Union[_models.SavingsPlanUpdateRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.SavingsPlanModel]:
        """Update savings plan by billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param savings_plan_order_id: Order ID of the savings plan. Required.
        :type savings_plan_order_id: str
        :param savings_plan_id: ID of the savings plan. Required.
        :type savings_plan_id: str
        :param body: Request body for patching a savings plan order alias. Is one of the following
         types: SavingsPlanUpdateRequest, JSON, IO[bytes] Required.
        :type body: ~azure.mgmt.billing.models.SavingsPlanUpdateRequest or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns SavingsPlanModel. The SavingsPlanModel is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.SavingsPlanModel]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.SavingsPlanModel] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._update_by_billing_account_initial(
                billing_account_name=billing_account_name,
                savings_plan_order_id=savings_plan_order_id,
                savings_plan_id=savings_plan_id,
                body=body,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.SavingsPlanModel, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.SavingsPlanModel].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.SavingsPlanModel](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace
    def list_by_savings_plan_order(
        self, billing_account_name: str, savings_plan_order_id: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.SavingsPlanModel"]:
        """List savings plans in an order by billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param savings_plan_order_id: Order ID of the savings plan. Required.
        :type savings_plan_order_id: str
        :return: An iterator like instance of SavingsPlanModel
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.SavingsPlanModel]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.SavingsPlanModel]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_savings_plans_list_by_savings_plan_order_request(
                    billing_account_name=billing_account_name,
                    savings_plan_order_id=savings_plan_order_id,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.SavingsPlanModel],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @overload
    async def validate_update_by_billing_account(
        self,
        billing_account_name: str,
        savings_plan_order_id: str,
        savings_plan_id: str,
        body: _models.SavingsPlanUpdateValidateRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.SavingsPlanValidateResponse:
        """Validate savings plan patch by billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param savings_plan_order_id: Order ID of the savings plan. Required.
        :type savings_plan_order_id: str
        :param savings_plan_id: ID of the savings plan. Required.
        :type savings_plan_id: str
        :param body: Request body for patching a savings plan order alias. Required.
        :type body: ~azure.mgmt.billing.models.SavingsPlanUpdateValidateRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: SavingsPlanValidateResponse. The SavingsPlanValidateResponse is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.billing.models.SavingsPlanValidateResponse
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def validate_update_by_billing_account(
        self,
        billing_account_name: str,
        savings_plan_order_id: str,
        savings_plan_id: str,
        body: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.SavingsPlanValidateResponse:
        """Validate savings plan patch by billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param savings_plan_order_id: Order ID of the savings plan. Required.
        :type savings_plan_order_id: str
        :param savings_plan_id: ID of the savings plan. Required.
        :type savings_plan_id: str
        :param body: Request body for patching a savings plan order alias. Required.
        :type body: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: SavingsPlanValidateResponse. The SavingsPlanValidateResponse is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.billing.models.SavingsPlanValidateResponse
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def validate_update_by_billing_account(
        self,
        billing_account_name: str,
        savings_plan_order_id: str,
        savings_plan_id: str,
        body: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.SavingsPlanValidateResponse:
        """Validate savings plan patch by billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param savings_plan_order_id: Order ID of the savings plan. Required.
        :type savings_plan_order_id: str
        :param savings_plan_id: ID of the savings plan. Required.
        :type savings_plan_id: str
        :param body: Request body for patching a savings plan order alias. Required.
        :type body: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: SavingsPlanValidateResponse. The SavingsPlanValidateResponse is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.billing.models.SavingsPlanValidateResponse
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def validate_update_by_billing_account(
        self,
        billing_account_name: str,
        savings_plan_order_id: str,
        savings_plan_id: str,
        body: Union[_models.SavingsPlanUpdateValidateRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.SavingsPlanValidateResponse:
        """Validate savings plan patch by billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param savings_plan_order_id: Order ID of the savings plan. Required.
        :type savings_plan_order_id: str
        :param savings_plan_id: ID of the savings plan. Required.
        :type savings_plan_id: str
        :param body: Request body for patching a savings plan order alias. Is one of the following
         types: SavingsPlanUpdateValidateRequest, JSON, IO[bytes] Required.
        :type body: ~azure.mgmt.billing.models.SavingsPlanUpdateValidateRequest or JSON or IO[bytes]
        :return: SavingsPlanValidateResponse. The SavingsPlanValidateResponse is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.billing.models.SavingsPlanValidateResponse
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.SavingsPlanValidateResponse] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(body, (IOBase, bytes)):
            _content = body
        else:
            _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_savings_plans_validate_update_by_billing_account_request(
            billing_account_name=billing_account_name,
            savings_plan_order_id=savings_plan_order_id,
            savings_plan_id=savings_plan_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.SavingsPlanValidateResponse, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class BillingPropertyOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s
        :attr:`billing_property` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: BillingManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, *, include_billing_country: bool = False, include_transition_status: bool = False, **kwargs: Any
    ) -> _models.BillingProperty:
        """Gets the billing properties for a subscription.

        :keyword include_billing_country: A flag that specifies whether or not to include billing
         country. Default value is False.
        :paramtype include_billing_country: bool
        :keyword include_transition_status: A flag that specifies whether or not to include transition
         status for billing accounts with agreement type Microsoft Customer Agreement. Default value is
         False.
        :paramtype include_transition_status: bool
        :return: BillingProperty. The BillingProperty is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.BillingProperty
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.BillingProperty] = kwargs.pop("cls", None)

        _request = build_billing_property_get_request(
            subscription_id=self._config.subscription_id,
            include_billing_country=include_billing_country,
            include_transition_status=include_transition_status,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.BillingProperty, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def update(
        self, parameters: _models.BillingProperty, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.BillingProperty:
        """Updates the billing property of a subscription. Currently, cost center can be updated for
        billing accounts with agreement type Microsoft Customer Agreement and subscription service
        usage address can be updated for billing accounts with agreement type Microsoft Online Service
        Program.

        :param parameters: A billing property. Required.
        :type parameters: ~azure.mgmt.billing.models.BillingProperty
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: BillingProperty. The BillingProperty is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.BillingProperty
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self, parameters: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.BillingProperty:
        """Updates the billing property of a subscription. Currently, cost center can be updated for
        billing accounts with agreement type Microsoft Customer Agreement and subscription service
        usage address can be updated for billing accounts with agreement type Microsoft Online Service
        Program.

        :param parameters: A billing property. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: BillingProperty. The BillingProperty is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.BillingProperty
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.BillingProperty:
        """Updates the billing property of a subscription. Currently, cost center can be updated for
        billing accounts with agreement type Microsoft Customer Agreement and subscription service
        usage address can be updated for billing accounts with agreement type Microsoft Online Service
        Program.

        :param parameters: A billing property. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: BillingProperty. The BillingProperty is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.BillingProperty
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self, parameters: Union[_models.BillingProperty, JSON, IO[bytes]], **kwargs: Any
    ) -> _models.BillingProperty:
        """Updates the billing property of a subscription. Currently, cost center can be updated for
        billing accounts with agreement type Microsoft Customer Agreement and subscription service
        usage address can be updated for billing accounts with agreement type Microsoft Online Service
        Program.

        :param parameters: A billing property. Is one of the following types: BillingProperty, JSON,
         IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.BillingProperty or JSON or IO[bytes]
        :return: BillingProperty. The BillingProperty is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.BillingProperty
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.BillingProperty] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_billing_property_update_request(
            subscription_id=self._config.subscription_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.BillingProperty, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class BillingRoleDefinitionOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s
        :attr:`billing_role_definition` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: BillingManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get_by_billing_profile(
        self, billing_account_name: str, billing_profile_name: str, role_definition_name: str, **kwargs: Any
    ) -> _models.BillingRoleDefinition:
        """Gets the definition for a role on a billing profile. The operation is supported for billing
        accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param role_definition_name: The ID that uniquely identifies a role definition. Required.
        :type role_definition_name: str
        :return: BillingRoleDefinition. The BillingRoleDefinition is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.BillingRoleDefinition
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.BillingRoleDefinition] = kwargs.pop("cls", None)

        _request = build_billing_role_definition_get_by_billing_profile_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            role_definition_name=role_definition_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.BillingRoleDefinition, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_billing_profile(
        self, billing_account_name: str, billing_profile_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingRoleDefinition"]:
        """Lists the role definitions for a billing profile. The operation is supported for billing
        accounts with agreement type Microsoft Partner Agreement, Microsoft Customer Agreement or
        Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :return: An iterator like instance of BillingRoleDefinition
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleDefinition]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingRoleDefinition]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_role_definition_list_by_billing_profile_request(
                    billing_account_name=billing_account_name,
                    billing_profile_name=billing_profile_name,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingRoleDefinition],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def get_by_customer(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        customer_name: str,
        role_definition_name: str,
        **kwargs: Any
    ) -> _models.BillingRoleDefinition:
        """Gets the definition for a role on a customer. The operation is supported only for billing
        accounts with agreement type Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :param role_definition_name: The ID that uniquely identifies a role definition. Required.
        :type role_definition_name: str
        :return: BillingRoleDefinition. The BillingRoleDefinition is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.BillingRoleDefinition
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.BillingRoleDefinition] = kwargs.pop("cls", None)

        _request = build_billing_role_definition_get_by_customer_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            customer_name=customer_name,
            role_definition_name=role_definition_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.BillingRoleDefinition, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_customer(
        self, billing_account_name: str, billing_profile_name: str, customer_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingRoleDefinition"]:
        """Lists the role definitions for a customer. The operation is supported for billing accounts with
        agreement type Microsoft Partner Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param customer_name: The ID that uniquely identifies a customer. Required.
        :type customer_name: str
        :return: An iterator like instance of BillingRoleDefinition
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleDefinition]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingRoleDefinition]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_role_definition_list_by_customer_request(
                    billing_account_name=billing_account_name,
                    billing_profile_name=billing_profile_name,
                    customer_name=customer_name,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingRoleDefinition],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def get_by_invoice_section(
        self,
        billing_account_name: str,
        billing_profile_name: str,
        invoice_section_name: str,
        role_definition_name: str,
        **kwargs: Any
    ) -> _models.BillingRoleDefinition:
        """Gets the definition for a role on an invoice section. The operation is supported only for
        billing accounts with agreement type Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :param role_definition_name: The ID that uniquely identifies a role definition. Required.
        :type role_definition_name: str
        :return: BillingRoleDefinition. The BillingRoleDefinition is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.BillingRoleDefinition
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.BillingRoleDefinition] = kwargs.pop("cls", None)

        _request = build_billing_role_definition_get_by_invoice_section_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            invoice_section_name=invoice_section_name,
            role_definition_name=role_definition_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.BillingRoleDefinition, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_invoice_section(
        self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingRoleDefinition"]:
        """Lists the role definitions for an invoice section. The operation is supported for billing
        accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param billing_profile_name: The ID that uniquely identifies a billing profile. Required.
        :type billing_profile_name: str
        :param invoice_section_name: The ID that uniquely identifies an invoice section. Required.
        :type invoice_section_name: str
        :return: An iterator like instance of BillingRoleDefinition
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleDefinition]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingRoleDefinition]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_role_definition_list_by_invoice_section_request(
                    billing_account_name=billing_account_name,
                    billing_profile_name=billing_profile_name,
                    invoice_section_name=invoice_section_name,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingRoleDefinition],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def get_by_billing_account(
        self, billing_account_name: str, role_definition_name: str, **kwargs: Any
    ) -> _models.BillingRoleDefinition:
        """Gets the definition for a role on a billing account. The operation is supported for billing
        accounts with agreement type Microsoft Partner Agreement, Microsoft Customer Agreement or
        Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param role_definition_name: The ID that uniquely identifies a role definition. Required.
        :type role_definition_name: str
        :return: BillingRoleDefinition. The BillingRoleDefinition is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.BillingRoleDefinition
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.BillingRoleDefinition] = kwargs.pop("cls", None)

        _request = build_billing_role_definition_get_by_billing_account_request(
            billing_account_name=billing_account_name,
            role_definition_name=role_definition_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.BillingRoleDefinition, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_billing_account(
        self, billing_account_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingRoleDefinition"]:
        """Lists the role definitions for a billing account. The operation is supported for billing
        accounts with agreement type Microsoft Partner Agreement, Microsoft Customer Agreement or
        Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :return: An iterator like instance of BillingRoleDefinition
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleDefinition]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingRoleDefinition]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_role_definition_list_by_billing_account_request(
                    billing_account_name=billing_account_name,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingRoleDefinition],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def get_by_department(
        self, billing_account_name: str, department_name: str, role_definition_name: str, **kwargs: Any
    ) -> _models.BillingRoleDefinition:
        """Gets the definition for a role on a department. The operation is supported for billing accounts
        with agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param department_name: The name of the department. Required.
        :type department_name: str
        :param role_definition_name: The ID that uniquely identifies a role definition. Required.
        :type role_definition_name: str
        :return: BillingRoleDefinition. The BillingRoleDefinition is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.BillingRoleDefinition
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.BillingRoleDefinition] = kwargs.pop("cls", None)

        _request = build_billing_role_definition_get_by_department_request(
            billing_account_name=billing_account_name,
            department_name=department_name,
            role_definition_name=role_definition_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.BillingRoleDefinition, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_department(
        self, billing_account_name: str, department_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingRoleDefinition"]:
        """List the definition for a department. The operation is supported for billing accounts with
        agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param department_name: The name of the department. Required.
        :type department_name: str
        :return: An iterator like instance of BillingRoleDefinition
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleDefinition]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingRoleDefinition]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_role_definition_list_by_department_request(
                    billing_account_name=billing_account_name,
                    department_name=department_name,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingRoleDefinition],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def get_by_enrollment_account(
        self, billing_account_name: str, enrollment_account_name: str, role_definition_name: str, **kwargs: Any
    ) -> _models.BillingRoleDefinition:
        """Gets the definition for a role on an enrollment account. The operation is supported for billing
        accounts with agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param enrollment_account_name: The name of the enrollment account. Required.
        :type enrollment_account_name: str
        :param role_definition_name: The ID that uniquely identifies a role definition. Required.
        :type role_definition_name: str
        :return: BillingRoleDefinition. The BillingRoleDefinition is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.BillingRoleDefinition
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.BillingRoleDefinition] = kwargs.pop("cls", None)

        _request = build_billing_role_definition_get_by_enrollment_account_request(
            billing_account_name=billing_account_name,
            enrollment_account_name=enrollment_account_name,
            role_definition_name=role_definition_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.BillingRoleDefinition, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_enrollment_account(
        self, billing_account_name: str, enrollment_account_name: str, **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingRoleDefinition"]:
        """List the definition for an enrollment account. The operation is supported for billing accounts
        with agreement type Enterprise Agreement.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param enrollment_account_name: The name of the enrollment account. Required.
        :type enrollment_account_name: str
        :return: An iterator like instance of BillingRoleDefinition
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleDefinition]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingRoleDefinition]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_role_definition_list_by_enrollment_account_request(
                    billing_account_name=billing_account_name,
                    enrollment_account_name=enrollment_account_name,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingRoleDefinition],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class SavingsPlanOrdersOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s
        :attr:`savings_plan_orders` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: BillingManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get_by_billing_account(
        self, billing_account_name: str, savings_plan_order_id: str, *, expand: Optional[str] = None, **kwargs: Any
    ) -> _models.SavingsPlanOrderModel:
        """Get a savings plan order by billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param savings_plan_order_id: Order ID of the savings plan. Required.
        :type savings_plan_order_id: str
        :keyword expand: May be used to expand the planInformation. Default value is None.
        :paramtype expand: str
        :return: SavingsPlanOrderModel. The SavingsPlanOrderModel is compatible with MutableMapping
        :rtype: ~azure.mgmt.billing.models.SavingsPlanOrderModel
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.SavingsPlanOrderModel] = kwargs.pop("cls", None)

        _request = build_savings_plan_orders_get_by_billing_account_request(
            billing_account_name=billing_account_name,
            savings_plan_order_id=savings_plan_order_id,
            expand=expand,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.SavingsPlanOrderModel, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def list_by_billing_account(
        self,
        billing_account_name: str,
        *,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        skiptoken: Optional[float] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.SavingsPlanOrderModel"]:
        """List all Savings plan orders by billing account.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword skiptoken: The number of savings plans to skip from the list before returning results.
         Default value is None.
        :paramtype skiptoken: float
        :return: An iterator like instance of SavingsPlanOrderModel
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.SavingsPlanOrderModel]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.SavingsPlanOrderModel]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_savings_plan_orders_list_by_billing_account_request(
                    billing_account_name=billing_account_name,
                    filter=filter,
                    order_by=order_by,
                    skiptoken=skiptoken,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.SavingsPlanOrderModel],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class BillingSubscriptionsAliasesOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s
        :attr:`billing_subscriptions_aliases` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: BillingManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(self, billing_account_name: str, alias_name: str, **kwargs: Any) -> _models.BillingSubscriptionAlias:
        """Gets a subscription by its alias ID.  The operation is supported for seat based billing
        subscriptions.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param alias_name: The ID that uniquely identifies a subscription alias. Required.
        :type alias_name: str
        :return: BillingSubscriptionAlias. The BillingSubscriptionAlias is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.billing.models.BillingSubscriptionAlias
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.BillingSubscriptionAlias] = kwargs.pop("cls", None)

        _request = build_billing_subscriptions_aliases_get_request(
            billing_account_name=billing_account_name,
            alias_name=alias_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.BillingSubscriptionAlias, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    async def _create_or_update_initial(
        self,
        billing_account_name: str,
        alias_name: str,
        parameters: Union[_models.BillingSubscriptionAlias, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_billing_subscriptions_aliases_create_or_update_request(
            billing_account_name=billing_account_name,
            alias_name=alias_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 201:
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_or_update(
        self,
        billing_account_name: str,
        alias_name: str,
        parameters: _models.BillingSubscriptionAlias,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingSubscriptionAlias]:
        """Creates or updates a billing subscription by its alias ID.  The operation is supported for seat
        based billing subscriptions.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param alias_name: The ID that uniquely identifies a subscription alias. Required.
        :type alias_name: str
        :param parameters: A billing subscription alias. Required.
        :type parameters: ~azure.mgmt.billing.models.BillingSubscriptionAlias
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingSubscriptionAlias. The
         BillingSubscriptionAlias is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingSubscriptionAlias]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        billing_account_name: str,
        alias_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingSubscriptionAlias]:
        """Creates or updates a billing subscription by its alias ID.  The operation is supported for seat
        based billing subscriptions.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param alias_name: The ID that uniquely identifies a subscription alias. Required.
        :type alias_name: str
        :param parameters: A billing subscription alias. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingSubscriptionAlias. The
         BillingSubscriptionAlias is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingSubscriptionAlias]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        billing_account_name: str,
        alias_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingSubscriptionAlias]:
        """Creates or updates a billing subscription by its alias ID.  The operation is supported for seat
        based billing subscriptions.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param alias_name: The ID that uniquely identifies a subscription alias. Required.
        :type alias_name: str
        :param parameters: A billing subscription alias. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BillingSubscriptionAlias. The
         BillingSubscriptionAlias is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingSubscriptionAlias]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_or_update(
        self,
        billing_account_name: str,
        alias_name: str,
        parameters: Union[_models.BillingSubscriptionAlias, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BillingSubscriptionAlias]:
        """Creates or updates a billing subscription by its alias ID.  The operation is supported for seat
        based billing subscriptions.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :param alias_name: The ID that uniquely identifies a subscription alias. Required.
        :type alias_name: str
        :param parameters: A billing subscription alias. Is one of the following types:
         BillingSubscriptionAlias, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.BillingSubscriptionAlias or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns BillingSubscriptionAlias. The
         BillingSubscriptionAlias is compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingSubscriptionAlias]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.BillingSubscriptionAlias] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_or_update_initial(
                billing_account_name=billing_account_name,
                alias_name=alias_name,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.BillingSubscriptionAlias, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.BillingSubscriptionAlias].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.BillingSubscriptionAlias](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace
    def list_by_billing_account(
        self,
        billing_account_name: str,
        *,
        include_deleted: bool = False,
        filter: Optional[str] = None,
        order_by: Optional[str] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        count: Optional[bool] = None,
        search: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.BillingSubscriptionAlias"]:
        """Lists the subscription aliases for a billing account. The operation is supported for seat based
        billing subscriptions.

        :param billing_account_name: The ID that uniquely identifies a billing account. Required.
        :type billing_account_name: str
        :keyword include_deleted: Can be used to get deleted billing subscriptions. Default value is
         False.
        :paramtype include_deleted: bool
        :keyword filter: The filter query option allows clients to filter a collection of resources
         that are addressed by a request URL. Default value is None.
        :paramtype filter: str
        :keyword order_by: The orderby query option allows clients to request resources in a particular
         order. Default value is None.
        :paramtype order_by: str
        :keyword top: The top query option requests the number of items in the queried collection to be
         included in the result. The maximum supported value for top is 50. Default value is None.
        :paramtype top: int
        :keyword skip: The skip query option requests the number of items in the queried collection
         that are to be skipped and not included in the result. Default value is None.
        :paramtype skip: int
        :keyword count: The count query option allows clients to request a count of the matching
         resources included with the resources in the response. Default value is None.
        :paramtype count: bool
        :keyword search: The search query option allows clients to request items within a collection
         matching a free-text search expression. search is only supported for string fields. Default
         value is None.
        :paramtype search: str
        :return: An iterator like instance of BillingSubscriptionAlias
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingSubscriptionAlias]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BillingSubscriptionAlias]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_billing_subscriptions_aliases_list_by_billing_account_request(
                    billing_account_name=billing_account_name,
                    include_deleted=include_deleted,
                    filter=filter,
                    order_by=order_by,
                    top=top,
                    skip=skip,
                    count=count,
                    search=search,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BillingSubscriptionAlias],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class AddressOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s
        :attr:`address` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: BillingManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @overload
    async def validate(
        self, parameters: _models.AddressDetails, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.AddressValidationResponse:
        """Validates an address. Use the operation to validate an address before using it as soldTo or a
        billTo address.

        :param parameters: The request body. Required.
        :type parameters: ~azure.mgmt.billing.models.AddressDetails
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: AddressValidationResponse. The AddressValidationResponse is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.billing.models.AddressValidationResponse
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def validate(
        self, parameters: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.AddressValidationResponse:
        """Validates an address. Use the operation to validate an address before using it as soldTo or a
        billTo address.

        :param parameters: The request body. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: AddressValidationResponse. The AddressValidationResponse is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.billing.models.AddressValidationResponse
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def validate(
        self, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.AddressValidationResponse:
        """Validates an address. Use the operation to validate an address before using it as soldTo or a
        billTo address.

        :param parameters: The request body. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: AddressValidationResponse. The AddressValidationResponse is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.billing.models.AddressValidationResponse
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def validate(
        self, parameters: Union[_models.AddressDetails, JSON, IO[bytes]], **kwargs: Any
    ) -> _models.AddressValidationResponse:
        """Validates an address. Use the operation to validate an address before using it as soldTo or a
        billTo address.

        :param parameters: The request body. Is one of the following types: AddressDetails, JSON,
         IO[bytes] Required.
        :type parameters: ~azure.mgmt.billing.models.AddressDetails or JSON or IO[bytes]
        :return: AddressValidationResponse. The AddressValidationResponse is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.billing.models.AddressValidationResponse
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.AddressValidationResponse] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_address_validate_request(
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.AddressValidationResponse, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore
