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

import typing
from ...core.client_wrapper import SyncClientWrapper
from ...requests.terminal_checkout import TerminalCheckoutParams
from ...core.request_options import RequestOptions
from ...core.http_response import HttpResponse
from ...types.create_terminal_checkout_response import CreateTerminalCheckoutResponse
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 ...requests.terminal_checkout_query import TerminalCheckoutQueryParams
from ...types.search_terminal_checkouts_response import SearchTerminalCheckoutsResponse
from ...types.get_terminal_checkout_response import GetTerminalCheckoutResponse
from ...core.jsonable_encoder import jsonable_encoder
from ...types.cancel_terminal_checkout_response import CancelTerminalCheckoutResponse
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 RawCheckoutsClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._client_wrapper = client_wrapper

    def create(
        self,
        *,
        idempotency_key: str,
        checkout: TerminalCheckoutParams,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[CreateTerminalCheckoutResponse]:
        """
        Creates a Terminal checkout request and sends it to the specified device to take a payment
        for the requested amount.

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

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

        checkout : TerminalCheckoutParams
            The checkout to create.

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

        Returns
        -------
        HttpResponse[CreateTerminalCheckoutResponse]
            Success
        """
        _response = self._client_wrapper.httpx_client.request(
            "v2/terminals/checkouts",
            method="POST",
            json={
                "idempotency_key": idempotency_key,
                "checkout": convert_and_respect_annotation_metadata(
                    object_=checkout, annotation=TerminalCheckoutParams, direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    CreateTerminalCheckoutResponse,
                    construct_type(
                        type_=CreateTerminalCheckoutResponse,  # 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 search(
        self,
        *,
        query: typing.Optional[TerminalCheckoutQueryParams] = OMIT,
        cursor: typing.Optional[str] = OMIT,
        limit: typing.Optional[int] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[SearchTerminalCheckoutsResponse]:
        """
        Returns a filtered list of Terminal checkout requests created by the application making the request. Only Terminal checkout requests created for the merchant scoped to the OAuth token are returned. Terminal checkout requests are available for 30 days.

        Parameters
        ----------
        query : typing.Optional[TerminalCheckoutQueryParams]
            Queries Terminal checkouts based on given conditions and the sort order.
            Leaving these unset returns all checkouts with the default sort order.

        cursor : typing.Optional[str]
            A pagination cursor returned by a previous call to this endpoint.
            Provide this cursor to retrieve the next set of results for the original query.
            See [Pagination](https://developer.squareup.com/docs/build-basics/common-api-patterns/pagination) for more information.

        limit : typing.Optional[int]
            Limits the number of results returned for a single request.

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

        Returns
        -------
        HttpResponse[SearchTerminalCheckoutsResponse]
            Success
        """
        _response = self._client_wrapper.httpx_client.request(
            "v2/terminals/checkouts/search",
            method="POST",
            json={
                "query": convert_and_respect_annotation_metadata(
                    object_=query, annotation=TerminalCheckoutQueryParams, direction="write"
                ),
                "cursor": cursor,
                "limit": limit,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    SearchTerminalCheckoutsResponse,
                    construct_type(
                        type_=SearchTerminalCheckoutsResponse,  # 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, checkout_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[GetTerminalCheckoutResponse]:
        """
        Retrieves a Terminal checkout request by `checkout_id`. Terminal checkout requests are available for 30 days.

        Parameters
        ----------
        checkout_id : str
            The unique ID for the desired `TerminalCheckout`.

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

        Returns
        -------
        HttpResponse[GetTerminalCheckoutResponse]
            Success
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v2/terminals/checkouts/{jsonable_encoder(checkout_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetTerminalCheckoutResponse,
                    construct_type(
                        type_=GetTerminalCheckoutResponse,  # 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 cancel(
        self, checkout_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[CancelTerminalCheckoutResponse]:
        """
        Cancels a Terminal checkout request if the status of the request permits it.

        Parameters
        ----------
        checkout_id : str
            The unique ID for the desired `TerminalCheckout`.

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

        Returns
        -------
        HttpResponse[CancelTerminalCheckoutResponse]
            Success
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v2/terminals/checkouts/{jsonable_encoder(checkout_id)}/cancel",
            method="POST",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    CancelTerminalCheckoutResponse,
                    construct_type(
                        type_=CancelTerminalCheckoutResponse,  # 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 AsyncRawCheckoutsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def create(
        self,
        *,
        idempotency_key: str,
        checkout: TerminalCheckoutParams,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[CreateTerminalCheckoutResponse]:
        """
        Creates a Terminal checkout request and sends it to the specified device to take a payment
        for the requested amount.

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

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

        checkout : TerminalCheckoutParams
            The checkout to create.

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

        Returns
        -------
        AsyncHttpResponse[CreateTerminalCheckoutResponse]
            Success
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v2/terminals/checkouts",
            method="POST",
            json={
                "idempotency_key": idempotency_key,
                "checkout": convert_and_respect_annotation_metadata(
                    object_=checkout, annotation=TerminalCheckoutParams, direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    CreateTerminalCheckoutResponse,
                    construct_type(
                        type_=CreateTerminalCheckoutResponse,  # 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 search(
        self,
        *,
        query: typing.Optional[TerminalCheckoutQueryParams] = OMIT,
        cursor: typing.Optional[str] = OMIT,
        limit: typing.Optional[int] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[SearchTerminalCheckoutsResponse]:
        """
        Returns a filtered list of Terminal checkout requests created by the application making the request. Only Terminal checkout requests created for the merchant scoped to the OAuth token are returned. Terminal checkout requests are available for 30 days.

        Parameters
        ----------
        query : typing.Optional[TerminalCheckoutQueryParams]
            Queries Terminal checkouts based on given conditions and the sort order.
            Leaving these unset returns all checkouts with the default sort order.

        cursor : typing.Optional[str]
            A pagination cursor returned by a previous call to this endpoint.
            Provide this cursor to retrieve the next set of results for the original query.
            See [Pagination](https://developer.squareup.com/docs/build-basics/common-api-patterns/pagination) for more information.

        limit : typing.Optional[int]
            Limits the number of results returned for a single request.

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

        Returns
        -------
        AsyncHttpResponse[SearchTerminalCheckoutsResponse]
            Success
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v2/terminals/checkouts/search",
            method="POST",
            json={
                "query": convert_and_respect_annotation_metadata(
                    object_=query, annotation=TerminalCheckoutQueryParams, direction="write"
                ),
                "cursor": cursor,
                "limit": limit,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    SearchTerminalCheckoutsResponse,
                    construct_type(
                        type_=SearchTerminalCheckoutsResponse,  # 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, checkout_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[GetTerminalCheckoutResponse]:
        """
        Retrieves a Terminal checkout request by `checkout_id`. Terminal checkout requests are available for 30 days.

        Parameters
        ----------
        checkout_id : str
            The unique ID for the desired `TerminalCheckout`.

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

        Returns
        -------
        AsyncHttpResponse[GetTerminalCheckoutResponse]
            Success
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v2/terminals/checkouts/{jsonable_encoder(checkout_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetTerminalCheckoutResponse,
                    construct_type(
                        type_=GetTerminalCheckoutResponse,  # 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 cancel(
        self, checkout_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[CancelTerminalCheckoutResponse]:
        """
        Cancels a Terminal checkout request if the status of the request permits it.

        Parameters
        ----------
        checkout_id : str
            The unique ID for the desired `TerminalCheckout`.

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

        Returns
        -------
        AsyncHttpResponse[CancelTerminalCheckoutResponse]
            Success
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v2/terminals/checkouts/{jsonable_encoder(checkout_id)}/cancel",
            method="POST",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    CancelTerminalCheckoutResponse,
                    construct_type(
                        type_=CancelTerminalCheckoutResponse,  # 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)
