# 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.pagination import AsyncPager, BaseHttpResponse, SyncPager
from ...core.request_options import RequestOptions
from ...core.serialization import convert_and_respect_annotation_metadata
from ...core.unchecked_base_model import construct_type
from ...requests.gift_card_activity import GiftCardActivityParams
from ...types.create_gift_card_activity_response import CreateGiftCardActivityResponse
from ...types.gift_card_activity import GiftCardActivity
from ...types.list_gift_card_activities_response import ListGiftCardActivitiesResponse

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


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

    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
        """
        _response = self._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(),
                    ),
                )
                _items = _parsed_response.gift_card_activities
                _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,
                )
                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 create(
        self,
        *,
        idempotency_key: str,
        gift_card_activity: GiftCardActivityParams,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[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
        -------
        HttpResponse[CreateGiftCardActivityResponse]
            Success
        """
        _response = self._client_wrapper.httpx_client.request(
            "v2/gift-cards/activities",
            method="POST",
            json={
                "idempotency_key": idempotency_key,
                "gift_card_activity": convert_and_respect_annotation_metadata(
                    object_=gift_card_activity, annotation=GiftCardActivityParams, direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    CreateGiftCardActivityResponse,
                    construct_type(
                        type_=CreateGiftCardActivityResponse,  # 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 AsyncRawActivitiesClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    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
        """
        _response = await self._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(),
                    ),
                )
                _items = _parsed_response.gift_card_activities
                _parsed_next = _parsed_response.cursor
                _has_next = _parsed_next is not None and _parsed_next != ""

                async def _get_next():
                    return await 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,
                    )

                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 create(
        self,
        *,
        idempotency_key: str,
        gift_card_activity: GiftCardActivityParams,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[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
        -------
        AsyncHttpResponse[CreateGiftCardActivityResponse]
            Success
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v2/gift-cards/activities",
            method="POST",
            json={
                "idempotency_key": idempotency_key,
                "gift_card_activity": convert_and_respect_annotation_metadata(
                    object_=gift_card_activity, annotation=GiftCardActivityParams, direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    CreateGiftCardActivityResponse,
                    construct_type(
                        type_=CreateGiftCardActivityResponse,  # 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)
