# 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.pagination import AsyncPager, BaseHttpResponse, SyncPager
from ...core.request_options import RequestOptions
from ...core.unchecked_base_model import construct_type
from ...types.customer_segment import CustomerSegment
from ...types.get_customer_segment_response import GetCustomerSegmentResponse
from ...types.list_customer_segments_response import ListCustomerSegmentsResponse


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

    def list(
        self,
        *,
        cursor: typing.Optional[str] = None,
        limit: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> SyncPager[CustomerSegment]:
        """
        Retrieves the list of customer segments of a business.

        Parameters
        ----------
        cursor : typing.Optional[str]
            A pagination cursor returned by previous calls to `ListCustomerSegments`.
            This cursor is used to retrieve the next set of query results.

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

        limit : typing.Optional[int]
            The maximum number of results to return in a single page. This limit is advisory. The response might contain more or fewer results.
            If the specified limit is less than 1 or greater than 50, Square returns a `400 VALUE_TOO_LOW` or `400 VALUE_TOO_HIGH` error. The default value is 50.

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

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

        Returns
        -------
        SyncPager[CustomerSegment]
            Success
        """
        _response = self._client_wrapper.httpx_client.request(
            "v2/customers/segments",
            method="GET",
            params={
                "cursor": cursor,
                "limit": limit,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ListCustomerSegmentsResponse,
                    construct_type(
                        type_=ListCustomerSegmentsResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _items = _parsed_response.segments
                _parsed_next = _parsed_response.cursor
                _has_next = _parsed_next is not None and _parsed_next != ""
                _get_next = lambda: self.list(
                    cursor=_parsed_next,
                    limit=limit,
                    request_options=request_options,
                )
                return SyncPager(
                    has_next=_has_next, items=_items, get_next=_get_next, response=BaseHttpResponse(response=_response)
                )
            _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(
        self, segment_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[GetCustomerSegmentResponse]:
        """
        Retrieves a specific customer segment as identified by the `segment_id` value.

        Parameters
        ----------
        segment_id : str
            The Square-issued ID of the customer segment.

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

        Returns
        -------
        HttpResponse[GetCustomerSegmentResponse]
            Success
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v2/customers/segments/{jsonable_encoder(segment_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetCustomerSegmentResponse,
                    construct_type(
                        type_=GetCustomerSegmentResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            _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 AsyncRawSegmentsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def list(
        self,
        *,
        cursor: typing.Optional[str] = None,
        limit: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncPager[CustomerSegment]:
        """
        Retrieves the list of customer segments of a business.

        Parameters
        ----------
        cursor : typing.Optional[str]
            A pagination cursor returned by previous calls to `ListCustomerSegments`.
            This cursor is used to retrieve the next set of query results.

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

        limit : typing.Optional[int]
            The maximum number of results to return in a single page. This limit is advisory. The response might contain more or fewer results.
            If the specified limit is less than 1 or greater than 50, Square returns a `400 VALUE_TOO_LOW` or `400 VALUE_TOO_HIGH` error. The default value is 50.

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

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

        Returns
        -------
        AsyncPager[CustomerSegment]
            Success
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v2/customers/segments",
            method="GET",
            params={
                "cursor": cursor,
                "limit": limit,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ListCustomerSegmentsResponse,
                    construct_type(
                        type_=ListCustomerSegmentsResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _items = _parsed_response.segments
                _parsed_next = _parsed_response.cursor
                _has_next = _parsed_next is not None and _parsed_next != ""

                async def _get_next():
                    return await self.list(
                        cursor=_parsed_next,
                        limit=limit,
                        request_options=request_options,
                    )

                return AsyncPager(
                    has_next=_has_next, items=_items, get_next=_get_next, response=BaseHttpResponse(response=_response)
                )
            _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(
        self, segment_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[GetCustomerSegmentResponse]:
        """
        Retrieves a specific customer segment as identified by the `segment_id` value.

        Parameters
        ----------
        segment_id : str
            The Square-issued ID of the customer segment.

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

        Returns
        -------
        AsyncHttpResponse[GetCustomerSegmentResponse]
            Success
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v2/customers/segments/{jsonable_encoder(segment_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetCustomerSegmentResponse,
                    construct_type(
                        type_=GetCustomerSegmentResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            _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)
