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

import typing
from ...core.client_wrapper import SyncClientWrapper
from .raw_client import RawGroupsClient
from ...core.request_options import RequestOptions
from ...core.pagination import SyncPager
from ...types.customer_group import CustomerGroup
from ...types.list_customer_groups_response import ListCustomerGroupsResponse
from ...core.unchecked_base_model import construct_type
from json.decoder import JSONDecodeError
from ...core.api_error import ApiError
from ...requests.customer_group import CustomerGroupParams
from ...types.create_customer_group_response import CreateCustomerGroupResponse
from ...types.get_customer_group_response import GetCustomerGroupResponse
from ...types.update_customer_group_response import UpdateCustomerGroupResponse
from ...types.delete_customer_group_response import DeleteCustomerGroupResponse
from ...types.add_group_to_customer_response import AddGroupToCustomerResponse
from ...types.remove_group_from_customer_response import RemoveGroupFromCustomerResponse
from ...core.client_wrapper import AsyncClientWrapper
from .raw_client import AsyncRawGroupsClient
from ...core.pagination import AsyncPager

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


class GroupsClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._raw_client = RawGroupsClient(client_wrapper=client_wrapper)

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

        Returns
        -------
        RawGroupsClient
        """
        return self._raw_client

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

        Parameters
        ----------
        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 your original query.

            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 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[CustomerGroup]
            Success

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

        client = Square(
            token="YOUR_TOKEN",
        )
        response = client.customers.groups.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/customers/groups",
            method="GET",
            params={
                "cursor": cursor,
                "limit": limit,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ListCustomerGroupsResponse,
                    construct_type(
                        type_=ListCustomerGroupsResponse,  # 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,
                    limit=limit,
                    request_options=request_options,
                )
                _items = _parsed_response.groups
                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,
        *,
        group: CustomerGroupParams,
        idempotency_key: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> CreateCustomerGroupResponse:
        """
        Creates a new customer group for a business.

        The request must include the `name` value of the group.

        Parameters
        ----------
        group : CustomerGroupParams
            The customer group to create.

        idempotency_key : typing.Optional[str]
            The idempotency key for the request. For more information, see [Idempotency](https://developer.squareup.com/docs/build-basics/common-api-patterns/idempotency).

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

        Returns
        -------
        CreateCustomerGroupResponse
            Success

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

        client = Square(
            token="YOUR_TOKEN",
        )
        client.customers.groups.create(
            group={"name": "Loyal Customers"},
        )
        """
        response = self._raw_client.create(
            group=group, idempotency_key=idempotency_key, request_options=request_options
        )
        return response.data

    def get(
        self, group_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> GetCustomerGroupResponse:
        """
        Retrieves a specific customer group as identified by the `group_id` value.

        Parameters
        ----------
        group_id : str
            The ID of the customer group to retrieve.

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

        Returns
        -------
        GetCustomerGroupResponse
            Success

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

        client = Square(
            token="YOUR_TOKEN",
        )
        client.customers.groups.get(
            group_id="group_id",
        )
        """
        response = self._raw_client.get(group_id, request_options=request_options)
        return response.data

    def update(
        self, group_id: str, *, group: CustomerGroupParams, request_options: typing.Optional[RequestOptions] = None
    ) -> UpdateCustomerGroupResponse:
        """
        Updates a customer group as identified by the `group_id` value.

        Parameters
        ----------
        group_id : str
            The ID of the customer group to update.

        group : CustomerGroupParams
            The `CustomerGroup` object including all the updates you want to make.

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

        Returns
        -------
        UpdateCustomerGroupResponse
            Success

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

        client = Square(
            token="YOUR_TOKEN",
        )
        client.customers.groups.update(
            group_id="group_id",
            group={"name": "Loyal Customers"},
        )
        """
        response = self._raw_client.update(group_id, group=group, request_options=request_options)
        return response.data

    def delete(
        self, group_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> DeleteCustomerGroupResponse:
        """
        Deletes a customer group as identified by the `group_id` value.

        Parameters
        ----------
        group_id : str
            The ID of the customer group to delete.

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

        Returns
        -------
        DeleteCustomerGroupResponse
            Success

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

        client = Square(
            token="YOUR_TOKEN",
        )
        client.customers.groups.delete(
            group_id="group_id",
        )
        """
        response = self._raw_client.delete(group_id, request_options=request_options)
        return response.data

    def add(
        self, customer_id: str, group_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AddGroupToCustomerResponse:
        """
        Adds a group membership to a customer.

        The customer is identified by the `customer_id` value
        and the customer group is identified by the `group_id` value.

        Parameters
        ----------
        customer_id : str
            The ID of the customer to add to a group.

        group_id : str
            The ID of the customer group to add the customer to.

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

        Returns
        -------
        AddGroupToCustomerResponse
            Success

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

        client = Square(
            token="YOUR_TOKEN",
        )
        client.customers.groups.add(
            customer_id="customer_id",
            group_id="group_id",
        )
        """
        response = self._raw_client.add(customer_id, group_id, request_options=request_options)
        return response.data

    def remove(
        self, customer_id: str, group_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> RemoveGroupFromCustomerResponse:
        """
        Removes a group membership from a customer.

        The customer is identified by the `customer_id` value
        and the customer group is identified by the `group_id` value.

        Parameters
        ----------
        customer_id : str
            The ID of the customer to remove from the group.

        group_id : str
            The ID of the customer group to remove the customer from.

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

        Returns
        -------
        RemoveGroupFromCustomerResponse
            Success

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

        client = Square(
            token="YOUR_TOKEN",
        )
        client.customers.groups.remove(
            customer_id="customer_id",
            group_id="group_id",
        )
        """
        response = self._raw_client.remove(customer_id, group_id, request_options=request_options)
        return response.data


class AsyncGroupsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._raw_client = AsyncRawGroupsClient(client_wrapper=client_wrapper)

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

        Returns
        -------
        AsyncRawGroupsClient
        """
        return self._raw_client

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

        Parameters
        ----------
        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 your original query.

            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 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[CustomerGroup]
            Success

        Examples
        --------
        import asyncio

        from square import AsyncSquare

        client = AsyncSquare(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            response = await client.customers.groups.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/customers/groups",
            method="GET",
            params={
                "cursor": cursor,
                "limit": limit,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ListCustomerGroupsResponse,
                    construct_type(
                        type_=ListCustomerGroupsResponse,  # 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,
                    limit=limit,
                    request_options=request_options,
                )
                _items = _parsed_response.groups
                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,
        *,
        group: CustomerGroupParams,
        idempotency_key: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> CreateCustomerGroupResponse:
        """
        Creates a new customer group for a business.

        The request must include the `name` value of the group.

        Parameters
        ----------
        group : CustomerGroupParams
            The customer group to create.

        idempotency_key : typing.Optional[str]
            The idempotency key for the request. For more information, see [Idempotency](https://developer.squareup.com/docs/build-basics/common-api-patterns/idempotency).

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

        Returns
        -------
        CreateCustomerGroupResponse
            Success

        Examples
        --------
        import asyncio

        from square import AsyncSquare

        client = AsyncSquare(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.customers.groups.create(
                group={"name": "Loyal Customers"},
            )


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

    async def get(
        self, group_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> GetCustomerGroupResponse:
        """
        Retrieves a specific customer group as identified by the `group_id` value.

        Parameters
        ----------
        group_id : str
            The ID of the customer group to retrieve.

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

        Returns
        -------
        GetCustomerGroupResponse
            Success

        Examples
        --------
        import asyncio

        from square import AsyncSquare

        client = AsyncSquare(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.customers.groups.get(
                group_id="group_id",
            )


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

    async def update(
        self, group_id: str, *, group: CustomerGroupParams, request_options: typing.Optional[RequestOptions] = None
    ) -> UpdateCustomerGroupResponse:
        """
        Updates a customer group as identified by the `group_id` value.

        Parameters
        ----------
        group_id : str
            The ID of the customer group to update.

        group : CustomerGroupParams
            The `CustomerGroup` object including all the updates you want to make.

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

        Returns
        -------
        UpdateCustomerGroupResponse
            Success

        Examples
        --------
        import asyncio

        from square import AsyncSquare

        client = AsyncSquare(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.customers.groups.update(
                group_id="group_id",
                group={"name": "Loyal Customers"},
            )


        asyncio.run(main())
        """
        response = await self._raw_client.update(group_id, group=group, request_options=request_options)
        return response.data

    async def delete(
        self, group_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> DeleteCustomerGroupResponse:
        """
        Deletes a customer group as identified by the `group_id` value.

        Parameters
        ----------
        group_id : str
            The ID of the customer group to delete.

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

        Returns
        -------
        DeleteCustomerGroupResponse
            Success

        Examples
        --------
        import asyncio

        from square import AsyncSquare

        client = AsyncSquare(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.customers.groups.delete(
                group_id="group_id",
            )


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

    async def add(
        self, customer_id: str, group_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AddGroupToCustomerResponse:
        """
        Adds a group membership to a customer.

        The customer is identified by the `customer_id` value
        and the customer group is identified by the `group_id` value.

        Parameters
        ----------
        customer_id : str
            The ID of the customer to add to a group.

        group_id : str
            The ID of the customer group to add the customer to.

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

        Returns
        -------
        AddGroupToCustomerResponse
            Success

        Examples
        --------
        import asyncio

        from square import AsyncSquare

        client = AsyncSquare(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.customers.groups.add(
                customer_id="customer_id",
                group_id="group_id",
            )


        asyncio.run(main())
        """
        response = await self._raw_client.add(customer_id, group_id, request_options=request_options)
        return response.data

    async def remove(
        self, customer_id: str, group_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> RemoveGroupFromCustomerResponse:
        """
        Removes a group membership from a customer.

        The customer is identified by the `customer_id` value
        and the customer group is identified by the `group_id` value.

        Parameters
        ----------
        customer_id : str
            The ID of the customer to remove from the group.

        group_id : str
            The ID of the customer group to remove the customer from.

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

        Returns
        -------
        RemoveGroupFromCustomerResponse
            Success

        Examples
        --------
        import asyncio

        from square import AsyncSquare

        client = AsyncSquare(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.customers.groups.remove(
                customer_id="customer_id",
                group_id="group_id",
            )


        asyncio.run(main())
        """
        response = await self._raw_client.remove(customer_id, group_id, request_options=request_options)
        return response.data
