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

import typing
from ..core.client_wrapper import SyncClientWrapper
from .raw_client import RawCardsClient
from ..types.sort_order import SortOrder
from ..core.request_options import RequestOptions
from ..core.pagination import SyncPager
from ..types.card import Card
from ..types.list_cards_response import ListCardsResponse
from ..core.unchecked_base_model import construct_type
from json.decoder import JSONDecodeError
from ..core.api_error import ApiError
from ..requests.card import CardParams
from ..types.create_card_response import CreateCardResponse
from ..types.get_card_response import GetCardResponse
from ..types.disable_card_response import DisableCardResponse
from ..core.client_wrapper import AsyncClientWrapper
from .raw_client import AsyncRawCardsClient
from ..core.pagination import AsyncPager

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


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

    @property
    def with_raw_response(self) -> RawCardsClient:
        """
        Retrieves a raw implementation of this client that returns raw responses.

        Returns
        -------
        RawCardsClient
        """
        return self._raw_client

    def list(
        self,
        *,
        cursor: typing.Optional[str] = None,
        customer_id: typing.Optional[str] = None,
        include_disabled: typing.Optional[bool] = None,
        reference_id: typing.Optional[str] = None,
        sort_order: typing.Optional[SortOrder] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> SyncPager[Card]:
        """
        Retrieves a list of cards owned by the account making the request.
        A max of 25 cards will be returned.

        Parameters
        ----------
        cursor : typing.Optional[str]
            A pagination cursor returned by a previous call to this endpoint.
            Provide this to retrieve the next set of results for your original query.

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

        customer_id : typing.Optional[str]
            Limit results to cards associated with the customer supplied.
            By default, all cards owned by the merchant are returned.

        include_disabled : typing.Optional[bool]
            Includes disabled cards.
            By default, all enabled cards owned by the merchant are returned.

        reference_id : typing.Optional[str]
            Limit results to cards associated with the reference_id supplied.

        sort_order : typing.Optional[SortOrder]
            Sorts the returned list by when the card was created with the specified order.
            This field defaults to ASC.

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

        Returns
        -------
        SyncPager[Card]
            Success

        Examples
        --------
        from square import Square

        client = Square(
            token="YOUR_TOKEN",
        )
        response = client.cards.list()
        for item in response:
            yield item
        # alternatively, you can paginate page-by-page
        for page in response.iter_pages():
            yield page
        """
        _response = self._raw_client._client_wrapper.httpx_client.request(
            "v2/cards",
            method="GET",
            params={
                "cursor": cursor,
                "customer_id": customer_id,
                "include_disabled": include_disabled,
                "reference_id": reference_id,
                "sort_order": sort_order,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ListCardsResponse,
                    construct_type(
                        type_=ListCardsResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _parsed_next = _parsed_response.cursor
                _has_next = _parsed_next is not None and _parsed_next != ""
                _get_next = lambda: self.list(
                    cursor=_parsed_next,
                    customer_id=customer_id,
                    include_disabled=include_disabled,
                    reference_id=reference_id,
                    sort_order=sort_order,
                    request_options=request_options,
                )
                _items = _parsed_response.cards
                return SyncPager(has_next=_has_next, items=_items, get_next=_get_next)
            _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 create(
        self,
        *,
        idempotency_key: str,
        source_id: str,
        card: CardParams,
        verification_token: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> 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
        -------
        CreateCardResponse
            Success

        Examples
        --------
        from square import Square

        client = Square(
            token="YOUR_TOKEN",
        )
        client.cards.create(
            idempotency_key="4935a656-a929-4792-b97c-8848be85c27c",
            source_id="cnon:uIbfJXhXETSP197M3GB",
            card={
                "cardholder_name": "Amelia Earhart",
                "billing_address": {
                    "address_line1": "500 Electric Ave",
                    "address_line2": "Suite 600",
                    "locality": "New York",
                    "administrative_district_level1": "NY",
                    "postal_code": "10003",
                    "country": "US",
                },
                "customer_id": "VDKXEEKPJN48QDG3BGGFAK05P8",
                "reference_id": "user-id-1",
            },
        )
        """
        response = self._raw_client.create(
            idempotency_key=idempotency_key,
            source_id=source_id,
            card=card,
            verification_token=verification_token,
            request_options=request_options,
        )
        return response.data

    def get(self, card_id: str, *, request_options: typing.Optional[RequestOptions] = None) -> 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
        -------
        GetCardResponse
            Success

        Examples
        --------
        from square import Square

        client = Square(
            token="YOUR_TOKEN",
        )
        client.cards.get(
            card_id="card_id",
        )
        """
        response = self._raw_client.get(card_id, request_options=request_options)
        return response.data

    def disable(self, card_id: str, *, request_options: typing.Optional[RequestOptions] = None) -> 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
        -------
        DisableCardResponse
            Success

        Examples
        --------
        from square import Square

        client = Square(
            token="YOUR_TOKEN",
        )
        client.cards.disable(
            card_id="card_id",
        )
        """
        response = self._raw_client.disable(card_id, request_options=request_options)
        return response.data


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

    @property
    def with_raw_response(self) -> AsyncRawCardsClient:
        """
        Retrieves a raw implementation of this client that returns raw responses.

        Returns
        -------
        AsyncRawCardsClient
        """
        return self._raw_client

    async def list(
        self,
        *,
        cursor: typing.Optional[str] = None,
        customer_id: typing.Optional[str] = None,
        include_disabled: typing.Optional[bool] = None,
        reference_id: typing.Optional[str] = None,
        sort_order: typing.Optional[SortOrder] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncPager[Card]:
        """
        Retrieves a list of cards owned by the account making the request.
        A max of 25 cards will be returned.

        Parameters
        ----------
        cursor : typing.Optional[str]
            A pagination cursor returned by a previous call to this endpoint.
            Provide this to retrieve the next set of results for your original query.

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

        customer_id : typing.Optional[str]
            Limit results to cards associated with the customer supplied.
            By default, all cards owned by the merchant are returned.

        include_disabled : typing.Optional[bool]
            Includes disabled cards.
            By default, all enabled cards owned by the merchant are returned.

        reference_id : typing.Optional[str]
            Limit results to cards associated with the reference_id supplied.

        sort_order : typing.Optional[SortOrder]
            Sorts the returned list by when the card was created with the specified order.
            This field defaults to ASC.

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

        Returns
        -------
        AsyncPager[Card]
            Success

        Examples
        --------
        import asyncio

        from square import AsyncSquare

        client = AsyncSquare(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            response = await client.cards.list()
            async for item in response:
                yield item
            # alternatively, you can paginate page-by-page
            async for page in response.iter_pages():
                yield page


        asyncio.run(main())
        """
        _response = await self._raw_client._client_wrapper.httpx_client.request(
            "v2/cards",
            method="GET",
            params={
                "cursor": cursor,
                "customer_id": customer_id,
                "include_disabled": include_disabled,
                "reference_id": reference_id,
                "sort_order": sort_order,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ListCardsResponse,
                    construct_type(
                        type_=ListCardsResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _parsed_next = _parsed_response.cursor
                _has_next = _parsed_next is not None and _parsed_next != ""
                _get_next = lambda: self.list(
                    cursor=_parsed_next,
                    customer_id=customer_id,
                    include_disabled=include_disabled,
                    reference_id=reference_id,
                    sort_order=sort_order,
                    request_options=request_options,
                )
                _items = _parsed_response.cards
                return AsyncPager(has_next=_has_next, items=_items, get_next=_get_next)
            _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 create(
        self,
        *,
        idempotency_key: str,
        source_id: str,
        card: CardParams,
        verification_token: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> 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
        -------
        CreateCardResponse
            Success

        Examples
        --------
        import asyncio

        from square import AsyncSquare

        client = AsyncSquare(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.cards.create(
                idempotency_key="4935a656-a929-4792-b97c-8848be85c27c",
                source_id="cnon:uIbfJXhXETSP197M3GB",
                card={
                    "cardholder_name": "Amelia Earhart",
                    "billing_address": {
                        "address_line1": "500 Electric Ave",
                        "address_line2": "Suite 600",
                        "locality": "New York",
                        "administrative_district_level1": "NY",
                        "postal_code": "10003",
                        "country": "US",
                    },
                    "customer_id": "VDKXEEKPJN48QDG3BGGFAK05P8",
                    "reference_id": "user-id-1",
                },
            )


        asyncio.run(main())
        """
        response = await self._raw_client.create(
            idempotency_key=idempotency_key,
            source_id=source_id,
            card=card,
            verification_token=verification_token,
            request_options=request_options,
        )
        return response.data

    async def get(self, card_id: str, *, request_options: typing.Optional[RequestOptions] = None) -> 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
        -------
        GetCardResponse
            Success

        Examples
        --------
        import asyncio

        from square import AsyncSquare

        client = AsyncSquare(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.cards.get(
                card_id="card_id",
            )


        asyncio.run(main())
        """
        response = await self._raw_client.get(card_id, request_options=request_options)
        return response.data

    async def disable(
        self, card_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> 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
        -------
        DisableCardResponse
            Success

        Examples
        --------
        import asyncio

        from square import AsyncSquare

        client = AsyncSquare(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.cards.disable(
                card_id="card_id",
            )


        asyncio.run(main())
        """
        response = await self._raw_client.disable(card_id, request_options=request_options)
        return response.data
