# 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.pydantic_utilities import parse_obj_as
from ..core.request_options import RequestOptions
from ..errors.unprocessable_entity_error import UnprocessableEntityError
from ..types.trigger_subscription_list_response import TriggerSubscriptionListResponse
from ..types.trigger_subscription_response import TriggerSubscriptionResponse

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


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

    def list_subscriptions(
        self,
        *,
        organization_id: str,
        skip: typing.Optional[int] = None,
        limit: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[TriggerSubscriptionListResponse]:
        """
        List all trigger subscriptions for the current user in the given organization.

        Parameters
        ----------
        organization_id : str
            Organization ID

        skip : typing.Optional[int]

        limit : typing.Optional[int]

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

        Returns
        -------
        HttpResponse[TriggerSubscriptionListResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/trigger-subscriptions",
            method="GET",
            params={
                "organization_id": organization_id,
                "skip": skip,
                "limit": limit,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    TriggerSubscriptionListResponse,
                    parse_obj_as(
                        type_=TriggerSubscriptionListResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    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)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def create_subscription(
        self,
        *,
        organization_id: str,
        provider: str,
        event_type: str,
        flow_id: str,
        trigger_name: str,
        api_key: str,
        connection_id: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[TriggerSubscriptionResponse]:
        """
        Subscribe a FlowPlate flow to a webhook event. Idempotent: if a subscription with the same (provider, event_type, connection_id, flow_id) already exists for this user, it is returned and re-enabled if disabled.

        Parameters
        ----------
        organization_id : str
            Organization ID

        provider : str
            Provider name (e.g., 'connector', 'freshdesk')

        event_type : str
            Event type (e.g., 'gmail_new_email', 'ticket_created')

        flow_id : str
            FlowPlate flow UUID to trigger

        trigger_name : str
            Trigger node display name in the flow (e.g., 'Answer Tickets')

        api_key : str
            FlowPlate API key for the flow owner (sk-...)

        connection_id : typing.Optional[str]
            Provider-specific account/connection ID. NULL matches all connections.

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

        Returns
        -------
        HttpResponse[TriggerSubscriptionResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/trigger-subscriptions",
            method="POST",
            params={
                "organization_id": organization_id,
            },
            json={
                "provider": provider,
                "event_type": event_type,
                "connection_id": connection_id,
                "flow_id": flow_id,
                "trigger_name": trigger_name,
                "api_key": api_key,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    TriggerSubscriptionResponse,
                    parse_obj_as(
                        type_=TriggerSubscriptionResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    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)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def get_subscription(
        self, subscription_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[TriggerSubscriptionResponse]:
        """
        Retrieve a single trigger subscription by ID. Only the owner can access it.

        Parameters
        ----------
        subscription_id : str

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

        Returns
        -------
        HttpResponse[TriggerSubscriptionResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/trigger-subscriptions/{jsonable_encoder(subscription_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    TriggerSubscriptionResponse,
                    parse_obj_as(
                        type_=TriggerSubscriptionResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    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)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def delete_subscription(
        self, subscription_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[None]:
        """
        Soft-delete a trigger subscription. It will no longer match incoming webhooks.

        Parameters
        ----------
        subscription_id : str

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

        Returns
        -------
        HttpResponse[None]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/trigger-subscriptions/{jsonable_encoder(subscription_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return HttpResponse(response=_response, data=None)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    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)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def update_subscription(
        self,
        subscription_id: str,
        *,
        provider: typing.Optional[str] = OMIT,
        event_type: typing.Optional[str] = OMIT,
        connection_id: typing.Optional[str] = OMIT,
        flow_id: typing.Optional[str] = OMIT,
        trigger_name: typing.Optional[str] = OMIT,
        api_key: typing.Optional[str] = OMIT,
        enabled: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[TriggerSubscriptionResponse]:
        """
        Update fields on a trigger subscription. If api_key is provided, it is re-encrypted at rest.

        Parameters
        ----------
        subscription_id : str

        provider : typing.Optional[str]

        event_type : typing.Optional[str]

        connection_id : typing.Optional[str]

        flow_id : typing.Optional[str]

        trigger_name : typing.Optional[str]

        api_key : typing.Optional[str]
            New API key (re-encrypted if provided)

        enabled : typing.Optional[bool]

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

        Returns
        -------
        HttpResponse[TriggerSubscriptionResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/trigger-subscriptions/{jsonable_encoder(subscription_id)}",
            method="PATCH",
            json={
                "provider": provider,
                "event_type": event_type,
                "connection_id": connection_id,
                "flow_id": flow_id,
                "trigger_name": trigger_name,
                "api_key": api_key,
                "enabled": enabled,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    TriggerSubscriptionResponse,
                    parse_obj_as(
                        type_=TriggerSubscriptionResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    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)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def create_subscription_s2s(
        self,
        *,
        organization_id: str,
        user_id: str,
        flowplate_master_key: str,
        provider: str,
        event_type: str,
        flow_id: str,
        trigger_name: str,
        api_key: str,
        connection_id: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[TriggerSubscriptionResponse]:
        """
        Called by FlowPlate when a user publishes a flow with trigger components. Authenticated via X-Flowplate-Master-Key. Idempotent: re-enables if the same subscription already exists.

        Parameters
        ----------
        organization_id : str
            Organization ID

        user_id : str
            User ID (flow owner)

        flowplate_master_key : str
            Flowplate master API key

        provider : str
            Provider name (e.g., 'connector', 'freshdesk')

        event_type : str
            Event type (e.g., 'gmail_new_email', 'ticket_created')

        flow_id : str
            FlowPlate flow UUID to trigger

        trigger_name : str
            Trigger node display name in the flow (e.g., 'Answer Tickets')

        api_key : str
            FlowPlate API key for the flow owner (sk-...)

        connection_id : typing.Optional[str]
            Provider-specific account/connection ID. NULL matches all connections.

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

        Returns
        -------
        HttpResponse[TriggerSubscriptionResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/trigger-subscriptions/by-flow",
            method="POST",
            params={
                "organization_id": organization_id,
                "user_id": user_id,
            },
            json={
                "provider": provider,
                "event_type": event_type,
                "connection_id": connection_id,
                "flow_id": flow_id,
                "trigger_name": trigger_name,
                "api_key": api_key,
            },
            headers={
                "content-type": "application/json",
                "x-flowplate-master-key": str(flowplate_master_key) if flowplate_master_key is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    TriggerSubscriptionResponse,
                    parse_obj_as(
                        type_=TriggerSubscriptionResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    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)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def delete_subscriptions_by_flow(
        self,
        flow_id: str,
        *,
        user_id: str,
        flowplate_master_key: str,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[typing.Dict[str, typing.Any]]:
        """
        Called by FlowPlate when a user unpublishes a flow. Soft-deletes all trigger subscriptions for the given flow_id. Authenticated via X-Flowplate-Master-Key.

        Parameters
        ----------
        flow_id : str

        user_id : str
            User ID (flow owner)

        flowplate_master_key : str
            Flowplate master API key

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

        Returns
        -------
        HttpResponse[typing.Dict[str, typing.Any]]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/trigger-subscriptions/by-flow/{jsonable_encoder(flow_id)}",
            method="DELETE",
            params={
                "user_id": user_id,
            },
            headers={
                "x-flowplate-master-key": str(flowplate_master_key) if flowplate_master_key is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Dict[str, typing.Any],
                    parse_obj_as(
                        type_=typing.Dict[str, typing.Any],  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    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)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)


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

    async def list_subscriptions(
        self,
        *,
        organization_id: str,
        skip: typing.Optional[int] = None,
        limit: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[TriggerSubscriptionListResponse]:
        """
        List all trigger subscriptions for the current user in the given organization.

        Parameters
        ----------
        organization_id : str
            Organization ID

        skip : typing.Optional[int]

        limit : typing.Optional[int]

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

        Returns
        -------
        AsyncHttpResponse[TriggerSubscriptionListResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/trigger-subscriptions",
            method="GET",
            params={
                "organization_id": organization_id,
                "skip": skip,
                "limit": limit,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    TriggerSubscriptionListResponse,
                    parse_obj_as(
                        type_=TriggerSubscriptionListResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    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)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def create_subscription(
        self,
        *,
        organization_id: str,
        provider: str,
        event_type: str,
        flow_id: str,
        trigger_name: str,
        api_key: str,
        connection_id: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[TriggerSubscriptionResponse]:
        """
        Subscribe a FlowPlate flow to a webhook event. Idempotent: if a subscription with the same (provider, event_type, connection_id, flow_id) already exists for this user, it is returned and re-enabled if disabled.

        Parameters
        ----------
        organization_id : str
            Organization ID

        provider : str
            Provider name (e.g., 'connector', 'freshdesk')

        event_type : str
            Event type (e.g., 'gmail_new_email', 'ticket_created')

        flow_id : str
            FlowPlate flow UUID to trigger

        trigger_name : str
            Trigger node display name in the flow (e.g., 'Answer Tickets')

        api_key : str
            FlowPlate API key for the flow owner (sk-...)

        connection_id : typing.Optional[str]
            Provider-specific account/connection ID. NULL matches all connections.

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

        Returns
        -------
        AsyncHttpResponse[TriggerSubscriptionResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/trigger-subscriptions",
            method="POST",
            params={
                "organization_id": organization_id,
            },
            json={
                "provider": provider,
                "event_type": event_type,
                "connection_id": connection_id,
                "flow_id": flow_id,
                "trigger_name": trigger_name,
                "api_key": api_key,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    TriggerSubscriptionResponse,
                    parse_obj_as(
                        type_=TriggerSubscriptionResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    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)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def get_subscription(
        self, subscription_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[TriggerSubscriptionResponse]:
        """
        Retrieve a single trigger subscription by ID. Only the owner can access it.

        Parameters
        ----------
        subscription_id : str

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

        Returns
        -------
        AsyncHttpResponse[TriggerSubscriptionResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/trigger-subscriptions/{jsonable_encoder(subscription_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    TriggerSubscriptionResponse,
                    parse_obj_as(
                        type_=TriggerSubscriptionResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    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)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def delete_subscription(
        self, subscription_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[None]:
        """
        Soft-delete a trigger subscription. It will no longer match incoming webhooks.

        Parameters
        ----------
        subscription_id : str

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

        Returns
        -------
        AsyncHttpResponse[None]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/trigger-subscriptions/{jsonable_encoder(subscription_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return AsyncHttpResponse(response=_response, data=None)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    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)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def update_subscription(
        self,
        subscription_id: str,
        *,
        provider: typing.Optional[str] = OMIT,
        event_type: typing.Optional[str] = OMIT,
        connection_id: typing.Optional[str] = OMIT,
        flow_id: typing.Optional[str] = OMIT,
        trigger_name: typing.Optional[str] = OMIT,
        api_key: typing.Optional[str] = OMIT,
        enabled: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[TriggerSubscriptionResponse]:
        """
        Update fields on a trigger subscription. If api_key is provided, it is re-encrypted at rest.

        Parameters
        ----------
        subscription_id : str

        provider : typing.Optional[str]

        event_type : typing.Optional[str]

        connection_id : typing.Optional[str]

        flow_id : typing.Optional[str]

        trigger_name : typing.Optional[str]

        api_key : typing.Optional[str]
            New API key (re-encrypted if provided)

        enabled : typing.Optional[bool]

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

        Returns
        -------
        AsyncHttpResponse[TriggerSubscriptionResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/trigger-subscriptions/{jsonable_encoder(subscription_id)}",
            method="PATCH",
            json={
                "provider": provider,
                "event_type": event_type,
                "connection_id": connection_id,
                "flow_id": flow_id,
                "trigger_name": trigger_name,
                "api_key": api_key,
                "enabled": enabled,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    TriggerSubscriptionResponse,
                    parse_obj_as(
                        type_=TriggerSubscriptionResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    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)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def create_subscription_s2s(
        self,
        *,
        organization_id: str,
        user_id: str,
        flowplate_master_key: str,
        provider: str,
        event_type: str,
        flow_id: str,
        trigger_name: str,
        api_key: str,
        connection_id: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[TriggerSubscriptionResponse]:
        """
        Called by FlowPlate when a user publishes a flow with trigger components. Authenticated via X-Flowplate-Master-Key. Idempotent: re-enables if the same subscription already exists.

        Parameters
        ----------
        organization_id : str
            Organization ID

        user_id : str
            User ID (flow owner)

        flowplate_master_key : str
            Flowplate master API key

        provider : str
            Provider name (e.g., 'connector', 'freshdesk')

        event_type : str
            Event type (e.g., 'gmail_new_email', 'ticket_created')

        flow_id : str
            FlowPlate flow UUID to trigger

        trigger_name : str
            Trigger node display name in the flow (e.g., 'Answer Tickets')

        api_key : str
            FlowPlate API key for the flow owner (sk-...)

        connection_id : typing.Optional[str]
            Provider-specific account/connection ID. NULL matches all connections.

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

        Returns
        -------
        AsyncHttpResponse[TriggerSubscriptionResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/trigger-subscriptions/by-flow",
            method="POST",
            params={
                "organization_id": organization_id,
                "user_id": user_id,
            },
            json={
                "provider": provider,
                "event_type": event_type,
                "connection_id": connection_id,
                "flow_id": flow_id,
                "trigger_name": trigger_name,
                "api_key": api_key,
            },
            headers={
                "content-type": "application/json",
                "x-flowplate-master-key": str(flowplate_master_key) if flowplate_master_key is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    TriggerSubscriptionResponse,
                    parse_obj_as(
                        type_=TriggerSubscriptionResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    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)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def delete_subscriptions_by_flow(
        self,
        flow_id: str,
        *,
        user_id: str,
        flowplate_master_key: str,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[typing.Dict[str, typing.Any]]:
        """
        Called by FlowPlate when a user unpublishes a flow. Soft-deletes all trigger subscriptions for the given flow_id. Authenticated via X-Flowplate-Master-Key.

        Parameters
        ----------
        flow_id : str

        user_id : str
            User ID (flow owner)

        flowplate_master_key : str
            Flowplate master API key

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

        Returns
        -------
        AsyncHttpResponse[typing.Dict[str, typing.Any]]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/trigger-subscriptions/by-flow/{jsonable_encoder(flow_id)}",
            method="DELETE",
            params={
                "user_id": user_id,
            },
            headers={
                "x-flowplate-master-key": str(flowplate_master_key) if flowplate_master_key is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Dict[str, typing.Any],
                    parse_obj_as(
                        type_=typing.Dict[str, typing.Any],  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    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)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
