# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.

from __future__ import annotations

import httpx

from ..._types import Body, Omit, Query, Headers, NoneType, NotGiven, omit, not_given
from ..._utils import maybe_transform, async_maybe_transform
from ..._compat import cached_property
from ..._resource import SyncAPIResource, AsyncAPIResource
from ..._response import (
    to_raw_response_wrapper,
    to_streamed_response_wrapper,
    async_to_raw_response_wrapper,
    async_to_streamed_response_wrapper,
)
from ...pagination import SyncCursorPage, AsyncCursorPage
from ...types.users import subscription_list_params, subscription_subscribe_params
from ..._base_client import AsyncPaginator, make_request_options
from ...types.users.subscription import Subscription

__all__ = ["SubscriptionsResource", "AsyncSubscriptionsResource"]


class SubscriptionsResource(SyncAPIResource):
    @cached_property
    def with_raw_response(self) -> SubscriptionsResourceWithRawResponse:
        """
        This property can be used as a prefix for any HTTP method call to return
        the raw response object instead of the parsed content.

        For more information, see https://www.github.com/stainless-sdks/notiflows-sdk-python#accessing-raw-response-data-eg-headers
        """
        return SubscriptionsResourceWithRawResponse(self)

    @cached_property
    def with_streaming_response(self) -> SubscriptionsResourceWithStreamingResponse:
        """
        An alternative to `.with_raw_response` that doesn't eagerly read the response body.

        For more information, see https://www.github.com/stainless-sdks/notiflows-sdk-python#with_streaming_response
        """
        return SubscriptionsResourceWithStreamingResponse(self)

    def retrieve(
        self,
        topic_name: str,
        *,
        user_external_id: str,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> Subscription:
        """
        Check if a user is subscribed to a specific topic.

        Args:
          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        if not user_external_id:
            raise ValueError(f"Expected a non-empty value for `user_external_id` but received {user_external_id!r}")
        if not topic_name:
            raise ValueError(f"Expected a non-empty value for `topic_name` but received {topic_name!r}")
        return self._get(
            f"/users/{user_external_id}/subscriptions/{topic_name}",
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=Subscription,
        )

    def list(
        self,
        user_external_id: str,
        *,
        after: str | Omit = omit,
        before: str | Omit = omit,
        created_after: str | Omit = omit,
        created_before: str | Omit = omit,
        limit: int | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> SyncCursorPage[Subscription]:
        """
        Retrieve all topic subscriptions for a user.

        Args:
          after: Cursor for fetching the next page

          before: Cursor for fetching the previous page

          created_after: Filter by created after (ISO 8601 datetime)

          created_before: Filter by created before (ISO 8601 datetime)

          limit: Number of items per page (default: 25, max: 1000)

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        if not user_external_id:
            raise ValueError(f"Expected a non-empty value for `user_external_id` but received {user_external_id!r}")
        return self._get_api_list(
            f"/users/{user_external_id}/subscriptions",
            page=SyncCursorPage[Subscription],
            options=make_request_options(
                extra_headers=extra_headers,
                extra_query=extra_query,
                extra_body=extra_body,
                timeout=timeout,
                query=maybe_transform(
                    {
                        "after": after,
                        "before": before,
                        "created_after": created_after,
                        "created_before": created_before,
                        "limit": limit,
                    },
                    subscription_list_params.SubscriptionListParams,
                ),
            ),
            model=Subscription,
        )

    def subscribe(
        self,
        user_external_id: str,
        *,
        topic_name: str,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> Subscription:
        """Subscribe a user to a topic.

        Topics are created automatically if they don't
        exist.

        **Idempotent:** If the user is already subscribed, returns the existing
        subscription with `200 OK`.

        Args:
          topic_name: Name of the topic to subscribe to. Topics are created automatically if they
              don't exist.

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        if not user_external_id:
            raise ValueError(f"Expected a non-empty value for `user_external_id` but received {user_external_id!r}")
        return self._post(
            f"/users/{user_external_id}/subscriptions",
            body=maybe_transform({"topic_name": topic_name}, subscription_subscribe_params.SubscriptionSubscribeParams),
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=Subscription,
        )

    def unsubscribe(
        self,
        topic_name: str,
        *,
        user_external_id: str,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> None:
        """Remove a user's subscription from a topic.

        The user will no longer receive
        notifications triggered for this topic.

        Args:
          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        if not user_external_id:
            raise ValueError(f"Expected a non-empty value for `user_external_id` but received {user_external_id!r}")
        if not topic_name:
            raise ValueError(f"Expected a non-empty value for `topic_name` but received {topic_name!r}")
        extra_headers = {"Accept": "*/*", **(extra_headers or {})}
        return self._delete(
            f"/users/{user_external_id}/subscriptions/{topic_name}",
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=NoneType,
        )


class AsyncSubscriptionsResource(AsyncAPIResource):
    @cached_property
    def with_raw_response(self) -> AsyncSubscriptionsResourceWithRawResponse:
        """
        This property can be used as a prefix for any HTTP method call to return
        the raw response object instead of the parsed content.

        For more information, see https://www.github.com/stainless-sdks/notiflows-sdk-python#accessing-raw-response-data-eg-headers
        """
        return AsyncSubscriptionsResourceWithRawResponse(self)

    @cached_property
    def with_streaming_response(self) -> AsyncSubscriptionsResourceWithStreamingResponse:
        """
        An alternative to `.with_raw_response` that doesn't eagerly read the response body.

        For more information, see https://www.github.com/stainless-sdks/notiflows-sdk-python#with_streaming_response
        """
        return AsyncSubscriptionsResourceWithStreamingResponse(self)

    async def retrieve(
        self,
        topic_name: str,
        *,
        user_external_id: str,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> Subscription:
        """
        Check if a user is subscribed to a specific topic.

        Args:
          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        if not user_external_id:
            raise ValueError(f"Expected a non-empty value for `user_external_id` but received {user_external_id!r}")
        if not topic_name:
            raise ValueError(f"Expected a non-empty value for `topic_name` but received {topic_name!r}")
        return await self._get(
            f"/users/{user_external_id}/subscriptions/{topic_name}",
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=Subscription,
        )

    def list(
        self,
        user_external_id: str,
        *,
        after: str | Omit = omit,
        before: str | Omit = omit,
        created_after: str | Omit = omit,
        created_before: str | Omit = omit,
        limit: int | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> AsyncPaginator[Subscription, AsyncCursorPage[Subscription]]:
        """
        Retrieve all topic subscriptions for a user.

        Args:
          after: Cursor for fetching the next page

          before: Cursor for fetching the previous page

          created_after: Filter by created after (ISO 8601 datetime)

          created_before: Filter by created before (ISO 8601 datetime)

          limit: Number of items per page (default: 25, max: 1000)

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        if not user_external_id:
            raise ValueError(f"Expected a non-empty value for `user_external_id` but received {user_external_id!r}")
        return self._get_api_list(
            f"/users/{user_external_id}/subscriptions",
            page=AsyncCursorPage[Subscription],
            options=make_request_options(
                extra_headers=extra_headers,
                extra_query=extra_query,
                extra_body=extra_body,
                timeout=timeout,
                query=maybe_transform(
                    {
                        "after": after,
                        "before": before,
                        "created_after": created_after,
                        "created_before": created_before,
                        "limit": limit,
                    },
                    subscription_list_params.SubscriptionListParams,
                ),
            ),
            model=Subscription,
        )

    async def subscribe(
        self,
        user_external_id: str,
        *,
        topic_name: str,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> Subscription:
        """Subscribe a user to a topic.

        Topics are created automatically if they don't
        exist.

        **Idempotent:** If the user is already subscribed, returns the existing
        subscription with `200 OK`.

        Args:
          topic_name: Name of the topic to subscribe to. Topics are created automatically if they
              don't exist.

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        if not user_external_id:
            raise ValueError(f"Expected a non-empty value for `user_external_id` but received {user_external_id!r}")
        return await self._post(
            f"/users/{user_external_id}/subscriptions",
            body=await async_maybe_transform(
                {"topic_name": topic_name}, subscription_subscribe_params.SubscriptionSubscribeParams
            ),
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=Subscription,
        )

    async def unsubscribe(
        self,
        topic_name: str,
        *,
        user_external_id: str,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> None:
        """Remove a user's subscription from a topic.

        The user will no longer receive
        notifications triggered for this topic.

        Args:
          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        if not user_external_id:
            raise ValueError(f"Expected a non-empty value for `user_external_id` but received {user_external_id!r}")
        if not topic_name:
            raise ValueError(f"Expected a non-empty value for `topic_name` but received {topic_name!r}")
        extra_headers = {"Accept": "*/*", **(extra_headers or {})}
        return await self._delete(
            f"/users/{user_external_id}/subscriptions/{topic_name}",
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=NoneType,
        )


class SubscriptionsResourceWithRawResponse:
    def __init__(self, subscriptions: SubscriptionsResource) -> None:
        self._subscriptions = subscriptions

        self.retrieve = to_raw_response_wrapper(
            subscriptions.retrieve,
        )
        self.list = to_raw_response_wrapper(
            subscriptions.list,
        )
        self.subscribe = to_raw_response_wrapper(
            subscriptions.subscribe,
        )
        self.unsubscribe = to_raw_response_wrapper(
            subscriptions.unsubscribe,
        )


class AsyncSubscriptionsResourceWithRawResponse:
    def __init__(self, subscriptions: AsyncSubscriptionsResource) -> None:
        self._subscriptions = subscriptions

        self.retrieve = async_to_raw_response_wrapper(
            subscriptions.retrieve,
        )
        self.list = async_to_raw_response_wrapper(
            subscriptions.list,
        )
        self.subscribe = async_to_raw_response_wrapper(
            subscriptions.subscribe,
        )
        self.unsubscribe = async_to_raw_response_wrapper(
            subscriptions.unsubscribe,
        )


class SubscriptionsResourceWithStreamingResponse:
    def __init__(self, subscriptions: SubscriptionsResource) -> None:
        self._subscriptions = subscriptions

        self.retrieve = to_streamed_response_wrapper(
            subscriptions.retrieve,
        )
        self.list = to_streamed_response_wrapper(
            subscriptions.list,
        )
        self.subscribe = to_streamed_response_wrapper(
            subscriptions.subscribe,
        )
        self.unsubscribe = to_streamed_response_wrapper(
            subscriptions.unsubscribe,
        )


class AsyncSubscriptionsResourceWithStreamingResponse:
    def __init__(self, subscriptions: AsyncSubscriptionsResource) -> None:
        self._subscriptions = subscriptions

        self.retrieve = async_to_streamed_response_wrapper(
            subscriptions.retrieve,
        )
        self.list = async_to_streamed_response_wrapper(
            subscriptions.list,
        )
        self.subscribe = async_to_streamed_response_wrapper(
            subscriptions.subscribe,
        )
        self.unsubscribe = async_to_streamed_response_wrapper(
            subscriptions.unsubscribe,
        )
