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

import typing
from ...core.client_wrapper import SyncClientWrapper
from .raw_client import RawActivitiesClient
from ...core.request_options import RequestOptions
from ...core.pagination import SyncPager
from ...types.gift_card_activity import GiftCardActivity
from ...types.list_gift_card_activities_response import ListGiftCardActivitiesResponse
from ...core.unchecked_base_model import construct_type
from json.decoder import JSONDecodeError
from ...core.api_error import ApiError
from ...requests.gift_card_activity import GiftCardActivityParams
from ...types.create_gift_card_activity_response import CreateGiftCardActivityResponse
from ...core.client_wrapper import AsyncClientWrapper
from .raw_client import AsyncRawActivitiesClient
from ...core.pagination import AsyncPager

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


class ActivitiesClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._raw_client = RawActivitiesClient(client_wrapper=client_wrapper)

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

        Returns
        -------
        RawActivitiesClient
        """
        return self._raw_client

    def list(
        self,
        *,
        gift_card_id: typing.Optional[str] = None,
        type: typing.Optional[str] = None,
        location_id: typing.Optional[str] = None,
        begin_time: typing.Optional[str] = None,
        end_time: typing.Optional[str] = None,
        limit: typing.Optional[int] = None,
        cursor: typing.Optional[str] = None,
        sort_order: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> SyncPager[GiftCardActivity]:
        """
        Lists gift card activities. By default, you get gift card activities for all
        gift cards in the seller's account. You can optionally specify query parameters to
        filter the list. For example, you can get a list of gift card activities for a gift card,
        for all gift cards in a specific region, or for activities within a time window.

        Parameters
        ----------
        gift_card_id : typing.Optional[str]
            If a gift card ID is provided, the endpoint returns activities related
            to the specified gift card. Otherwise, the endpoint returns all gift card activities for
            the seller.

        type : typing.Optional[str]
            If a [type](entity:GiftCardActivityType) is provided, the endpoint returns gift card activities of the specified type.
            Otherwise, the endpoint returns all types of gift card activities.

        location_id : typing.Optional[str]
            If a location ID is provided, the endpoint returns gift card activities for the specified location.
            Otherwise, the endpoint returns gift card activities for all locations.

        begin_time : typing.Optional[str]
            The timestamp for the beginning of the reporting period, in RFC 3339 format.
            This start time is inclusive. The default value is the current time minus one year.

        end_time : typing.Optional[str]
            The timestamp for the end of the reporting period, in RFC 3339 format.
            This end time is inclusive. The default value is the current time.

        limit : typing.Optional[int]
            If a limit is provided, the endpoint returns the specified number
            of results (or fewer) per page. The maximum value is 100. The default value is 50.
            For more information, see [Pagination](https://developer.squareup.com/docs/working-with-apis/pagination).

        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.
            If a cursor is not provided, the endpoint returns the first page of the results.
            For more information, see [Pagination](https://developer.squareup.com/docs/working-with-apis/pagination).

        sort_order : typing.Optional[str]
            The order in which the endpoint returns the activities, based on `created_at`.
            - `ASC` - Oldest to newest.
            - `DESC` - Newest to oldest (default).

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

        Returns
        -------
        SyncPager[GiftCardActivity]
            Success

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

        client = Square(
            token="YOUR_TOKEN",
        )
        response = client.gift_cards.activities.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/gift-cards/activities",
            method="GET",
            params={
                "gift_card_id": gift_card_id,
                "type": type,
                "location_id": location_id,
                "begin_time": begin_time,
                "end_time": end_time,
                "limit": limit,
                "cursor": cursor,
                "sort_order": sort_order,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ListGiftCardActivitiesResponse,
                    construct_type(
                        type_=ListGiftCardActivitiesResponse,  # 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(
                    gift_card_id=gift_card_id,
                    type=type,
                    location_id=location_id,
                    begin_time=begin_time,
                    end_time=end_time,
                    limit=limit,
                    cursor=_parsed_next,
                    sort_order=sort_order,
                    request_options=request_options,
                )
                _items = _parsed_response.gift_card_activities
                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,
        gift_card_activity: GiftCardActivityParams,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> CreateGiftCardActivityResponse:
        """
        Creates a gift card activity to manage the balance or state of a [gift card](entity:GiftCard).
        For example, create an `ACTIVATE` activity to activate a gift card with an initial balance before first use.

        Parameters
        ----------
        idempotency_key : str
            A unique string that identifies the `CreateGiftCardActivity` request.

        gift_card_activity : GiftCardActivityParams
            The activity to create for the gift card. This activity must specify `gift_card_id` or `gift_card_gan` for the target
            gift card, the `location_id` where the activity occurred, and the activity `type` along with the corresponding activity details.

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

        Returns
        -------
        CreateGiftCardActivityResponse
            Success

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

        client = Square(
            token="YOUR_TOKEN",
        )
        client.gift_cards.activities.create(
            idempotency_key="U16kfr-kA70er-q4Rsym-7U7NnY",
            gift_card_activity={
                "type": "ACTIVATE",
                "location_id": "81FN9BNFZTKS4",
                "gift_card_id": "gftc:6d55a72470d940c6ba09c0ab8ad08d20",
                "activate_activity_details": {
                    "order_id": "jJNGHm4gLI6XkFbwtiSLqK72KkAZY",
                    "line_item_uid": "eIWl7X0nMuO9Ewbh0ChIx",
                },
            },
        )
        """
        response = self._raw_client.create(
            idempotency_key=idempotency_key, gift_card_activity=gift_card_activity, request_options=request_options
        )
        return response.data


class AsyncActivitiesClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._raw_client = AsyncRawActivitiesClient(client_wrapper=client_wrapper)

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

        Returns
        -------
        AsyncRawActivitiesClient
        """
        return self._raw_client

    async def list(
        self,
        *,
        gift_card_id: typing.Optional[str] = None,
        type: typing.Optional[str] = None,
        location_id: typing.Optional[str] = None,
        begin_time: typing.Optional[str] = None,
        end_time: typing.Optional[str] = None,
        limit: typing.Optional[int] = None,
        cursor: typing.Optional[str] = None,
        sort_order: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncPager[GiftCardActivity]:
        """
        Lists gift card activities. By default, you get gift card activities for all
        gift cards in the seller's account. You can optionally specify query parameters to
        filter the list. For example, you can get a list of gift card activities for a gift card,
        for all gift cards in a specific region, or for activities within a time window.

        Parameters
        ----------
        gift_card_id : typing.Optional[str]
            If a gift card ID is provided, the endpoint returns activities related
            to the specified gift card. Otherwise, the endpoint returns all gift card activities for
            the seller.

        type : typing.Optional[str]
            If a [type](entity:GiftCardActivityType) is provided, the endpoint returns gift card activities of the specified type.
            Otherwise, the endpoint returns all types of gift card activities.

        location_id : typing.Optional[str]
            If a location ID is provided, the endpoint returns gift card activities for the specified location.
            Otherwise, the endpoint returns gift card activities for all locations.

        begin_time : typing.Optional[str]
            The timestamp for the beginning of the reporting period, in RFC 3339 format.
            This start time is inclusive. The default value is the current time minus one year.

        end_time : typing.Optional[str]
            The timestamp for the end of the reporting period, in RFC 3339 format.
            This end time is inclusive. The default value is the current time.

        limit : typing.Optional[int]
            If a limit is provided, the endpoint returns the specified number
            of results (or fewer) per page. The maximum value is 100. The default value is 50.
            For more information, see [Pagination](https://developer.squareup.com/docs/working-with-apis/pagination).

        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.
            If a cursor is not provided, the endpoint returns the first page of the results.
            For more information, see [Pagination](https://developer.squareup.com/docs/working-with-apis/pagination).

        sort_order : typing.Optional[str]
            The order in which the endpoint returns the activities, based on `created_at`.
            - `ASC` - Oldest to newest.
            - `DESC` - Newest to oldest (default).

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

        Returns
        -------
        AsyncPager[GiftCardActivity]
            Success

        Examples
        --------
        import asyncio

        from square import AsyncSquare

        client = AsyncSquare(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            response = await client.gift_cards.activities.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/gift-cards/activities",
            method="GET",
            params={
                "gift_card_id": gift_card_id,
                "type": type,
                "location_id": location_id,
                "begin_time": begin_time,
                "end_time": end_time,
                "limit": limit,
                "cursor": cursor,
                "sort_order": sort_order,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ListGiftCardActivitiesResponse,
                    construct_type(
                        type_=ListGiftCardActivitiesResponse,  # 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(
                    gift_card_id=gift_card_id,
                    type=type,
                    location_id=location_id,
                    begin_time=begin_time,
                    end_time=end_time,
                    limit=limit,
                    cursor=_parsed_next,
                    sort_order=sort_order,
                    request_options=request_options,
                )
                _items = _parsed_response.gift_card_activities
                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,
        gift_card_activity: GiftCardActivityParams,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> CreateGiftCardActivityResponse:
        """
        Creates a gift card activity to manage the balance or state of a [gift card](entity:GiftCard).
        For example, create an `ACTIVATE` activity to activate a gift card with an initial balance before first use.

        Parameters
        ----------
        idempotency_key : str
            A unique string that identifies the `CreateGiftCardActivity` request.

        gift_card_activity : GiftCardActivityParams
            The activity to create for the gift card. This activity must specify `gift_card_id` or `gift_card_gan` for the target
            gift card, the `location_id` where the activity occurred, and the activity `type` along with the corresponding activity details.

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

        Returns
        -------
        CreateGiftCardActivityResponse
            Success

        Examples
        --------
        import asyncio

        from square import AsyncSquare

        client = AsyncSquare(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.gift_cards.activities.create(
                idempotency_key="U16kfr-kA70er-q4Rsym-7U7NnY",
                gift_card_activity={
                    "type": "ACTIVATE",
                    "location_id": "81FN9BNFZTKS4",
                    "gift_card_id": "gftc:6d55a72470d940c6ba09c0ab8ad08d20",
                    "activate_activity_details": {
                        "order_id": "jJNGHm4gLI6XkFbwtiSLqK72KkAZY",
                        "line_item_uid": "eIWl7X0nMuO9Ewbh0ChIx",
                    },
                },
            )


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