# This file was auto-generated by Fern from our API Definition.

import typing
from json.decoder import JSONDecodeError

from ..core.api_error import ApiError
from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.http_response import AsyncHttpResponse, HttpResponse
from ..core.jsonable_encoder import jsonable_encoder
from ..core.pydantic_utilities import parse_obj_as
from ..core.request_options import RequestOptions
from ..core.serialization import convert_and_respect_annotation_metadata
from ..errors.bad_request_error import BadRequestError
from ..errors.internal_server_error import InternalServerError
from ..errors.service_unavailable_error import ServiceUnavailableError
from ..errors.unauthorized_error import UnauthorizedError
from ..types.ach_validation import AchValidation
from ..types.entrypointfield import Entrypointfield
from ..types.force_customer_creation import ForceCustomerCreation
from ..types.idempotency_key import IdempotencyKey
from ..types.payabli_api_response import PayabliApiResponse
from ..types.payabli_api_response_paymethod_delete import PayabliApiResponsePaymethodDelete
from ..types.payor_data_request import PayorDataRequest
from ..types.source import Source
from ..types.subdomain import Subdomain
from .types.add_method_response import AddMethodResponse
from .types.create_anonymous import CreateAnonymous
from .types.get_method_response import GetMethodResponse
from .types.request_token_storage_payment_method import RequestTokenStoragePaymentMethod
from .types.temporary import Temporary

# this is used as the default value for optional parameters
OMIT = typing.cast(typing.Any, ...)


class RawTokenStorageClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._client_wrapper = client_wrapper

    def add_method(
        self,
        *,
        create_anonymous: CreateAnonymous,
        temporary: Temporary,
        ach_validation: typing.Optional[AchValidation] = None,
        force_customer_creation: typing.Optional[ForceCustomerCreation] = None,
        idempotency_key: typing.Optional[IdempotencyKey] = None,
        customer_data: typing.Optional[PayorDataRequest] = OMIT,
        entry_point: typing.Optional[Entrypointfield] = OMIT,
        fallback_auth: typing.Optional[bool] = OMIT,
        fallback_auth_amount: typing.Optional[int] = OMIT,
        method_description: typing.Optional[str] = OMIT,
        payment_method: typing.Optional[RequestTokenStoragePaymentMethod] = OMIT,
        source: typing.Optional[Source] = OMIT,
        subdomain: typing.Optional[Subdomain] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[AddMethodResponse]:
        """
        Saves a payment method for reuse. This call exchanges sensitive payment information for a token that can be used to process future transactions. The `ReferenceId` value in the response is the `storedMethodId` to use with transactions.

        Parameters
        ----------
        create_anonymous : CreateAnonymous

        temporary : Temporary

        ach_validation : typing.Optional[AchValidation]

        force_customer_creation : typing.Optional[ForceCustomerCreation]

        idempotency_key : typing.Optional[IdempotencyKey]

        customer_data : typing.Optional[PayorDataRequest]
            Object describing the Customer/Payor owner of payment method. Required for POST requests. Which fields are required depends on the paypoint's custom identifier settings.

        entry_point : typing.Optional[Entrypointfield]
            Entrypoint identifier. Required for POST requests.

        fallback_auth : typing.Optional[bool]
            When `true`, if tokenization fails, Payabli will attempt an authorization transaction to request a permanent token for the card. If the authorization is successful, the card will be tokenized and the authorization will be voided automatically.

        fallback_auth_amount : typing.Optional[int]
            The amount for the `fallbackAuth` transaction. Defaults to one dollar (`100`).

        method_description : typing.Optional[str]
            Custom description for stored payment method.

        payment_method : typing.Optional[RequestTokenStoragePaymentMethod]
            Information about the payment method for the transaction.

        source : typing.Optional[Source]
            Custom identifier to indicate the source for the request

        subdomain : typing.Optional[Subdomain]

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[AddMethodResponse]
            Success
        """
        _response = self._client_wrapper.httpx_client.request(
            "TokenStorage/add",
            method="POST",
            params={
                "achValidation": ach_validation,
                "createAnonymous": create_anonymous,
                "forceCustomerCreation": force_customer_creation,
                "temporary": temporary,
            },
            json={
                "customerData": convert_and_respect_annotation_metadata(
                    object_=customer_data, annotation=PayorDataRequest, direction="write"
                ),
                "entryPoint": entry_point,
                "fallbackAuth": fallback_auth,
                "fallbackAuthAmount": fallback_auth_amount,
                "methodDescription": method_description,
                "paymentMethod": convert_and_respect_annotation_metadata(
                    object_=payment_method, annotation=RequestTokenStoragePaymentMethod, direction="write"
                ),
                "source": source,
                "subdomain": subdomain,
            },
            headers={
                "content-type": "application/json",
                "idempotencyKey": str(idempotency_key) if idempotency_key is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    AddMethodResponse,
                    parse_obj_as(
                        type_=AddMethodResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 503:
                raise ServiceUnavailableError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        PayabliApiResponse,
                        parse_obj_as(
                            type_=PayabliApiResponse,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def get_method(
        self,
        method_id: str,
        *,
        card_expiration_format: typing.Optional[int] = None,
        include_temporary: typing.Optional[bool] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[GetMethodResponse]:
        """
        Retrieves details for a saved payment method.

        Parameters
        ----------
        method_id : str
            The saved payment method ID.

        card_expiration_format : typing.Optional[int]
            Format for card expiration dates in the response.

            Accepted values:

            - 0: default, no formatting. Expiration dates are returned in the format they're saved in.

            - 1: MMYY

            - 2: MM/YY

        include_temporary : typing.Optional[bool]
            When `true`, the request will include temporary tokens in the search and return details for a matching temporary token. The default behavior searches only for permanent tokens.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[GetMethodResponse]
            Success
        """
        _response = self._client_wrapper.httpx_client.request(
            f"TokenStorage/{jsonable_encoder(method_id)}",
            method="GET",
            params={
                "cardExpirationFormat": card_expiration_format,
                "includeTemporary": include_temporary,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetMethodResponse,
                    parse_obj_as(
                        type_=GetMethodResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 503:
                raise ServiceUnavailableError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        PayabliApiResponse,
                        parse_obj_as(
                            type_=PayabliApiResponse,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def remove_method(
        self, method_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[PayabliApiResponsePaymethodDelete]:
        """
        Deletes a saved payment method.

        Parameters
        ----------
        method_id : str
            The saved payment method ID.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[PayabliApiResponsePaymethodDelete]
            Success
        """
        _response = self._client_wrapper.httpx_client.request(
            f"TokenStorage/{jsonable_encoder(method_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    PayabliApiResponsePaymethodDelete,
                    parse_obj_as(
                        type_=PayabliApiResponsePaymethodDelete,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 503:
                raise ServiceUnavailableError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        PayabliApiResponse,
                        parse_obj_as(
                            type_=PayabliApiResponse,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def update_method(
        self,
        method_id: str,
        *,
        ach_validation: typing.Optional[AchValidation] = None,
        customer_data: typing.Optional[PayorDataRequest] = OMIT,
        entry_point: typing.Optional[Entrypointfield] = OMIT,
        fallback_auth: typing.Optional[bool] = OMIT,
        fallback_auth_amount: typing.Optional[int] = OMIT,
        method_description: typing.Optional[str] = OMIT,
        payment_method: typing.Optional[RequestTokenStoragePaymentMethod] = OMIT,
        source: typing.Optional[Source] = OMIT,
        subdomain: typing.Optional[Subdomain] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[PayabliApiResponsePaymethodDelete]:
        """
        Updates a saved payment method.

        Parameters
        ----------
        method_id : str
            The saved payment method ID.

        ach_validation : typing.Optional[AchValidation]

        customer_data : typing.Optional[PayorDataRequest]
            Object describing the Customer/Payor owner of payment method. Required for POST requests. Which fields are required depends on the paypoint's custom identifier settings.

        entry_point : typing.Optional[Entrypointfield]
            Entrypoint identifier. Required for POST requests.

        fallback_auth : typing.Optional[bool]
            When `true`, if tokenization fails, Payabli will attempt an authorization transaction to request a permanent token for the card. If the authorization is successful, the card will be tokenized and the authorization will be voided automatically.

        fallback_auth_amount : typing.Optional[int]
            The amount for the `fallbackAuth` transaction. Defaults to one dollar (`100`).

        method_description : typing.Optional[str]
            Custom description for stored payment method.

        payment_method : typing.Optional[RequestTokenStoragePaymentMethod]
            Information about the payment method for the transaction.

        source : typing.Optional[Source]
            Custom identifier to indicate the source for the request

        subdomain : typing.Optional[Subdomain]

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[PayabliApiResponsePaymethodDelete]
            Success
        """
        _response = self._client_wrapper.httpx_client.request(
            f"TokenStorage/{jsonable_encoder(method_id)}",
            method="PUT",
            params={
                "achValidation": ach_validation,
            },
            json={
                "customerData": convert_and_respect_annotation_metadata(
                    object_=customer_data, annotation=PayorDataRequest, direction="write"
                ),
                "entryPoint": entry_point,
                "fallbackAuth": fallback_auth,
                "fallbackAuthAmount": fallback_auth_amount,
                "methodDescription": method_description,
                "paymentMethod": convert_and_respect_annotation_metadata(
                    object_=payment_method, annotation=RequestTokenStoragePaymentMethod, direction="write"
                ),
                "source": source,
                "subdomain": subdomain,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    PayabliApiResponsePaymethodDelete,
                    parse_obj_as(
                        type_=PayabliApiResponsePaymethodDelete,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 503:
                raise ServiceUnavailableError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        PayabliApiResponse,
                        parse_obj_as(
                            type_=PayabliApiResponse,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)


class AsyncRawTokenStorageClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def add_method(
        self,
        *,
        create_anonymous: CreateAnonymous,
        temporary: Temporary,
        ach_validation: typing.Optional[AchValidation] = None,
        force_customer_creation: typing.Optional[ForceCustomerCreation] = None,
        idempotency_key: typing.Optional[IdempotencyKey] = None,
        customer_data: typing.Optional[PayorDataRequest] = OMIT,
        entry_point: typing.Optional[Entrypointfield] = OMIT,
        fallback_auth: typing.Optional[bool] = OMIT,
        fallback_auth_amount: typing.Optional[int] = OMIT,
        method_description: typing.Optional[str] = OMIT,
        payment_method: typing.Optional[RequestTokenStoragePaymentMethod] = OMIT,
        source: typing.Optional[Source] = OMIT,
        subdomain: typing.Optional[Subdomain] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[AddMethodResponse]:
        """
        Saves a payment method for reuse. This call exchanges sensitive payment information for a token that can be used to process future transactions. The `ReferenceId` value in the response is the `storedMethodId` to use with transactions.

        Parameters
        ----------
        create_anonymous : CreateAnonymous

        temporary : Temporary

        ach_validation : typing.Optional[AchValidation]

        force_customer_creation : typing.Optional[ForceCustomerCreation]

        idempotency_key : typing.Optional[IdempotencyKey]

        customer_data : typing.Optional[PayorDataRequest]
            Object describing the Customer/Payor owner of payment method. Required for POST requests. Which fields are required depends on the paypoint's custom identifier settings.

        entry_point : typing.Optional[Entrypointfield]
            Entrypoint identifier. Required for POST requests.

        fallback_auth : typing.Optional[bool]
            When `true`, if tokenization fails, Payabli will attempt an authorization transaction to request a permanent token for the card. If the authorization is successful, the card will be tokenized and the authorization will be voided automatically.

        fallback_auth_amount : typing.Optional[int]
            The amount for the `fallbackAuth` transaction. Defaults to one dollar (`100`).

        method_description : typing.Optional[str]
            Custom description for stored payment method.

        payment_method : typing.Optional[RequestTokenStoragePaymentMethod]
            Information about the payment method for the transaction.

        source : typing.Optional[Source]
            Custom identifier to indicate the source for the request

        subdomain : typing.Optional[Subdomain]

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[AddMethodResponse]
            Success
        """
        _response = await self._client_wrapper.httpx_client.request(
            "TokenStorage/add",
            method="POST",
            params={
                "achValidation": ach_validation,
                "createAnonymous": create_anonymous,
                "forceCustomerCreation": force_customer_creation,
                "temporary": temporary,
            },
            json={
                "customerData": convert_and_respect_annotation_metadata(
                    object_=customer_data, annotation=PayorDataRequest, direction="write"
                ),
                "entryPoint": entry_point,
                "fallbackAuth": fallback_auth,
                "fallbackAuthAmount": fallback_auth_amount,
                "methodDescription": method_description,
                "paymentMethod": convert_and_respect_annotation_metadata(
                    object_=payment_method, annotation=RequestTokenStoragePaymentMethod, direction="write"
                ),
                "source": source,
                "subdomain": subdomain,
            },
            headers={
                "content-type": "application/json",
                "idempotencyKey": str(idempotency_key) if idempotency_key is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    AddMethodResponse,
                    parse_obj_as(
                        type_=AddMethodResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 503:
                raise ServiceUnavailableError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        PayabliApiResponse,
                        parse_obj_as(
                            type_=PayabliApiResponse,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def get_method(
        self,
        method_id: str,
        *,
        card_expiration_format: typing.Optional[int] = None,
        include_temporary: typing.Optional[bool] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[GetMethodResponse]:
        """
        Retrieves details for a saved payment method.

        Parameters
        ----------
        method_id : str
            The saved payment method ID.

        card_expiration_format : typing.Optional[int]
            Format for card expiration dates in the response.

            Accepted values:

            - 0: default, no formatting. Expiration dates are returned in the format they're saved in.

            - 1: MMYY

            - 2: MM/YY

        include_temporary : typing.Optional[bool]
            When `true`, the request will include temporary tokens in the search and return details for a matching temporary token. The default behavior searches only for permanent tokens.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[GetMethodResponse]
            Success
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"TokenStorage/{jsonable_encoder(method_id)}",
            method="GET",
            params={
                "cardExpirationFormat": card_expiration_format,
                "includeTemporary": include_temporary,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetMethodResponse,
                    parse_obj_as(
                        type_=GetMethodResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 503:
                raise ServiceUnavailableError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        PayabliApiResponse,
                        parse_obj_as(
                            type_=PayabliApiResponse,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def remove_method(
        self, method_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[PayabliApiResponsePaymethodDelete]:
        """
        Deletes a saved payment method.

        Parameters
        ----------
        method_id : str
            The saved payment method ID.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[PayabliApiResponsePaymethodDelete]
            Success
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"TokenStorage/{jsonable_encoder(method_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    PayabliApiResponsePaymethodDelete,
                    parse_obj_as(
                        type_=PayabliApiResponsePaymethodDelete,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 503:
                raise ServiceUnavailableError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        PayabliApiResponse,
                        parse_obj_as(
                            type_=PayabliApiResponse,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def update_method(
        self,
        method_id: str,
        *,
        ach_validation: typing.Optional[AchValidation] = None,
        customer_data: typing.Optional[PayorDataRequest] = OMIT,
        entry_point: typing.Optional[Entrypointfield] = OMIT,
        fallback_auth: typing.Optional[bool] = OMIT,
        fallback_auth_amount: typing.Optional[int] = OMIT,
        method_description: typing.Optional[str] = OMIT,
        payment_method: typing.Optional[RequestTokenStoragePaymentMethod] = OMIT,
        source: typing.Optional[Source] = OMIT,
        subdomain: typing.Optional[Subdomain] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[PayabliApiResponsePaymethodDelete]:
        """
        Updates a saved payment method.

        Parameters
        ----------
        method_id : str
            The saved payment method ID.

        ach_validation : typing.Optional[AchValidation]

        customer_data : typing.Optional[PayorDataRequest]
            Object describing the Customer/Payor owner of payment method. Required for POST requests. Which fields are required depends on the paypoint's custom identifier settings.

        entry_point : typing.Optional[Entrypointfield]
            Entrypoint identifier. Required for POST requests.

        fallback_auth : typing.Optional[bool]
            When `true`, if tokenization fails, Payabli will attempt an authorization transaction to request a permanent token for the card. If the authorization is successful, the card will be tokenized and the authorization will be voided automatically.

        fallback_auth_amount : typing.Optional[int]
            The amount for the `fallbackAuth` transaction. Defaults to one dollar (`100`).

        method_description : typing.Optional[str]
            Custom description for stored payment method.

        payment_method : typing.Optional[RequestTokenStoragePaymentMethod]
            Information about the payment method for the transaction.

        source : typing.Optional[Source]
            Custom identifier to indicate the source for the request

        subdomain : typing.Optional[Subdomain]

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[PayabliApiResponsePaymethodDelete]
            Success
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"TokenStorage/{jsonable_encoder(method_id)}",
            method="PUT",
            params={
                "achValidation": ach_validation,
            },
            json={
                "customerData": convert_and_respect_annotation_metadata(
                    object_=customer_data, annotation=PayorDataRequest, direction="write"
                ),
                "entryPoint": entry_point,
                "fallbackAuth": fallback_auth,
                "fallbackAuthAmount": fallback_auth_amount,
                "methodDescription": method_description,
                "paymentMethod": convert_and_respect_annotation_metadata(
                    object_=payment_method, annotation=RequestTokenStoragePaymentMethod, direction="write"
                ),
                "source": source,
                "subdomain": subdomain,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    PayabliApiResponsePaymethodDelete,
                    parse_obj_as(
                        type_=PayabliApiResponsePaymethodDelete,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 503:
                raise ServiceUnavailableError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        PayabliApiResponse,
                        parse_obj_as(
                            type_=PayabliApiResponse,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
