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

import typing
from ..core.client_wrapper import SyncClientWrapper
from ..requests.card import CardParams
from ..core.request_options import RequestOptions
from ..core.http_response import HttpResponse
from ..types.create_card_response import CreateCardResponse
from ..core.serialization import convert_and_respect_annotation_metadata
from ..core.unchecked_base_model import construct_type
from json.decoder import JSONDecodeError
from ..core.api_error import ApiError
from ..types.get_card_response import GetCardResponse
from ..core.jsonable_encoder import jsonable_encoder
from ..types.disable_card_response import DisableCardResponse
from ..core.client_wrapper import AsyncClientWrapper
from ..core.http_response import AsyncHttpResponse

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


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

    def create(
        self,
        *,
        idempotency_key: str,
        source_id: str,
        card: CardParams,
        verification_token: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[CreateCardResponse]:
        """
        Adds a card on file to an existing merchant.

        Parameters
        ----------
        idempotency_key : str
            A unique string that identifies this CreateCard request. Keys can be
            any valid string and must be unique for every request.

            Max: 45 characters

            See [Idempotency keys](https://developer.squareup.com/docs/build-basics/common-api-patterns/idempotency) for more information.

        source_id : str
            The ID of the source which represents the card information to be stored. This can be a card nonce or a payment id.

        card : CardParams
            Payment details associated with the card to be stored.

        verification_token : typing.Optional[str]
            An identifying token generated by [Payments.verifyBuyer()](https://developer.squareup.com/reference/sdks/web/payments/objects/Payments#Payments.verifyBuyer).
            Verification tokens encapsulate customer device information and 3-D Secure
            challenge results to indicate that Square has verified the buyer identity.

            See the [SCA Overview](https://developer.squareup.com/docs/sca-overview).

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

        Returns
        -------
        HttpResponse[CreateCardResponse]
            Success
        """
        _response = self._client_wrapper.httpx_client.request(
            "v2/cards",
            method="POST",
            json={
                "idempotency_key": idempotency_key,
                "source_id": source_id,
                "verification_token": verification_token,
                "card": convert_and_respect_annotation_metadata(object_=card, annotation=CardParams, direction="write"),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    CreateCardResponse,
                    construct_type(
                        type_=CreateCardResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def get(
        self, card_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[GetCardResponse]:
        """
        Retrieves details for a specific Card.

        Parameters
        ----------
        card_id : str
            Unique ID for the desired Card.

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

        Returns
        -------
        HttpResponse[GetCardResponse]
            Success
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v2/cards/{jsonable_encoder(card_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetCardResponse,
                    construct_type(
                        type_=GetCardResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def disable(
        self, card_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[DisableCardResponse]:
        """
        Disables the card, preventing any further updates or charges.
        Disabling an already disabled card is allowed but has no effect.

        Parameters
        ----------
        card_id : str
            Unique ID for the desired Card.

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

        Returns
        -------
        HttpResponse[DisableCardResponse]
            Success
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v2/cards/{jsonable_encoder(card_id)}/disable",
            method="POST",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    DisableCardResponse,
                    construct_type(
                        type_=DisableCardResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)


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

    async def create(
        self,
        *,
        idempotency_key: str,
        source_id: str,
        card: CardParams,
        verification_token: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[CreateCardResponse]:
        """
        Adds a card on file to an existing merchant.

        Parameters
        ----------
        idempotency_key : str
            A unique string that identifies this CreateCard request. Keys can be
            any valid string and must be unique for every request.

            Max: 45 characters

            See [Idempotency keys](https://developer.squareup.com/docs/build-basics/common-api-patterns/idempotency) for more information.

        source_id : str
            The ID of the source which represents the card information to be stored. This can be a card nonce or a payment id.

        card : CardParams
            Payment details associated with the card to be stored.

        verification_token : typing.Optional[str]
            An identifying token generated by [Payments.verifyBuyer()](https://developer.squareup.com/reference/sdks/web/payments/objects/Payments#Payments.verifyBuyer).
            Verification tokens encapsulate customer device information and 3-D Secure
            challenge results to indicate that Square has verified the buyer identity.

            See the [SCA Overview](https://developer.squareup.com/docs/sca-overview).

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

        Returns
        -------
        AsyncHttpResponse[CreateCardResponse]
            Success
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v2/cards",
            method="POST",
            json={
                "idempotency_key": idempotency_key,
                "source_id": source_id,
                "verification_token": verification_token,
                "card": convert_and_respect_annotation_metadata(object_=card, annotation=CardParams, direction="write"),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    CreateCardResponse,
                    construct_type(
                        type_=CreateCardResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def get(
        self, card_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[GetCardResponse]:
        """
        Retrieves details for a specific Card.

        Parameters
        ----------
        card_id : str
            Unique ID for the desired Card.

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

        Returns
        -------
        AsyncHttpResponse[GetCardResponse]
            Success
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v2/cards/{jsonable_encoder(card_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetCardResponse,
                    construct_type(
                        type_=GetCardResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def disable(
        self, card_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[DisableCardResponse]:
        """
        Disables the card, preventing any further updates or charges.
        Disabling an already disabled card is allowed but has no effect.

        Parameters
        ----------
        card_id : str
            Unique ID for the desired Card.

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

        Returns
        -------
        AsyncHttpResponse[DisableCardResponse]
            Success
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v2/cards/{jsonable_encoder(card_id)}/disable",
            method="POST",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    DisableCardResponse,
                    construct_type(
                        type_=DisableCardResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)
