# 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 encode_path_param
from ....core.pagination import AsyncPager, SyncPager
from ....core.parse_error import ParsingError
from ....core.pydantic_utilities import parse_obj_as
from ....core.request_options import RequestOptions
from ....core.serialization import convert_and_respect_annotation_metadata
from ....errors.bad_request_error import BadRequestError
from ....errors.forbidden_error import ForbiddenError
from ....errors.too_many_requests_error import TooManyRequestsError
from ....errors.unauthorized_error import UnauthorizedError
from ....types.action_binding import ActionBinding
from ....types.action_binding_with_ref import ActionBindingWithRef
from ....types.action_trigger_type_enum import ActionTriggerTypeEnum
from ....types.list_action_bindings_paginated_response_content import ListActionBindingsPaginatedResponseContent
from ....types.update_action_bindings_response_content import UpdateActionBindingsResponseContent
from pydantic import ValidationError

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


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

    def list(
        self,
        trigger_id: ActionTriggerTypeEnum,
        *,
        page: typing.Optional[int] = 0,
        per_page: typing.Optional[int] = 50,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> SyncPager[ActionBinding, ListActionBindingsPaginatedResponseContent]:
        """
        Retrieve the actions that are bound to a trigger. Once an action is created and deployed, it must be attached (i.e. bound) to a trigger so that it will be executed as part of a flow. The list of actions returned reflects the order in which they will be executed during the appropriate flow.

        Parameters
        ----------
        trigger_id : ActionTriggerTypeEnum
            An actions extensibility point.

        page : typing.Optional[int]
            Use this field to request a specific page of the list results.

        per_page : typing.Optional[int]
            The maximum number of results to be returned in a single request. 20 by default

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

        Returns
        -------
        SyncPager[ActionBinding, ListActionBindingsPaginatedResponseContent]
            The bindings were retrieved.
        """
        page = page if page is not None else 0

        _response = self._client_wrapper.httpx_client.request(
            f"actions/triggers/{encode_path_param(trigger_id)}/bindings",
            method="GET",
            params={
                "page": page,
                "per_page": per_page,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ListActionBindingsPaginatedResponseContent,
                    parse_obj_as(
                        type_=ListActionBindingsPaginatedResponseContent,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _items = _parsed_response.bindings
                _has_next = len(_items or []) > 0
                _get_next = lambda: self.list(
                    trigger_id,
                    page=page + 1,
                    per_page=per_page,
                    request_options=request_options,
                )
                return SyncPager(has_next=_has_next, items=_items, get_next=_get_next, response=_parsed_response)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 429:
                raise TooManyRequestsError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def update_many(
        self,
        trigger_id: ActionTriggerTypeEnum,
        *,
        bindings: typing.Optional[typing.Sequence[ActionBindingWithRef]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[UpdateActionBindingsResponseContent]:
        """
        Update the actions that are bound (i.e. attached) to a trigger. Once an action is created and deployed, it must be attached (i.e. bound) to a trigger so that it will be executed as part of a flow. The order in which the actions are provided will determine the order in which they are executed.

        Parameters
        ----------
        trigger_id : ActionTriggerTypeEnum
            An actions extensibility point.

        bindings : typing.Optional[typing.Sequence[ActionBindingWithRef]]
            The actions that will be bound to this trigger. The order in which they are included will be the order in which they are executed.

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

        Returns
        -------
        HttpResponse[UpdateActionBindingsResponseContent]
            The bindings were updated.
        """
        _response = self._client_wrapper.httpx_client.request(
            f"actions/triggers/{encode_path_param(trigger_id)}/bindings",
            method="PATCH",
            json={
                "bindings": convert_and_respect_annotation_metadata(
                    object_=bindings, annotation=typing.Sequence[ActionBindingWithRef], direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    UpdateActionBindingsResponseContent,
                    parse_obj_as(
                        type_=UpdateActionBindingsResponseContent,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 429:
                raise TooManyRequestsError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)


class AsyncRawBindingsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def list(
        self,
        trigger_id: ActionTriggerTypeEnum,
        *,
        page: typing.Optional[int] = 0,
        per_page: typing.Optional[int] = 50,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncPager[ActionBinding, ListActionBindingsPaginatedResponseContent]:
        """
        Retrieve the actions that are bound to a trigger. Once an action is created and deployed, it must be attached (i.e. bound) to a trigger so that it will be executed as part of a flow. The list of actions returned reflects the order in which they will be executed during the appropriate flow.

        Parameters
        ----------
        trigger_id : ActionTriggerTypeEnum
            An actions extensibility point.

        page : typing.Optional[int]
            Use this field to request a specific page of the list results.

        per_page : typing.Optional[int]
            The maximum number of results to be returned in a single request. 20 by default

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

        Returns
        -------
        AsyncPager[ActionBinding, ListActionBindingsPaginatedResponseContent]
            The bindings were retrieved.
        """
        page = page if page is not None else 0

        _response = await self._client_wrapper.httpx_client.request(
            f"actions/triggers/{encode_path_param(trigger_id)}/bindings",
            method="GET",
            params={
                "page": page,
                "per_page": per_page,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ListActionBindingsPaginatedResponseContent,
                    parse_obj_as(
                        type_=ListActionBindingsPaginatedResponseContent,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _items = _parsed_response.bindings
                _has_next = len(_items or []) > 0

                async def _get_next():
                    return await self.list(
                        trigger_id,
                        page=page + 1,
                        per_page=per_page,
                        request_options=request_options,
                    )

                return AsyncPager(has_next=_has_next, items=_items, get_next=_get_next, response=_parsed_response)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 429:
                raise TooManyRequestsError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def update_many(
        self,
        trigger_id: ActionTriggerTypeEnum,
        *,
        bindings: typing.Optional[typing.Sequence[ActionBindingWithRef]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[UpdateActionBindingsResponseContent]:
        """
        Update the actions that are bound (i.e. attached) to a trigger. Once an action is created and deployed, it must be attached (i.e. bound) to a trigger so that it will be executed as part of a flow. The order in which the actions are provided will determine the order in which they are executed.

        Parameters
        ----------
        trigger_id : ActionTriggerTypeEnum
            An actions extensibility point.

        bindings : typing.Optional[typing.Sequence[ActionBindingWithRef]]
            The actions that will be bound to this trigger. The order in which they are included will be the order in which they are executed.

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

        Returns
        -------
        AsyncHttpResponse[UpdateActionBindingsResponseContent]
            The bindings were updated.
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"actions/triggers/{encode_path_param(trigger_id)}/bindings",
            method="PATCH",
            json={
                "bindings": convert_and_respect_annotation_metadata(
                    object_=bindings, annotation=typing.Sequence[ActionBindingWithRef], direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    UpdateActionBindingsResponseContent,
                    parse_obj_as(
                        type_=UpdateActionBindingsResponseContent,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 429:
                raise TooManyRequestsError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
