# 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.pydantic_utilities import parse_obj_as
from ..core.request_options import RequestOptions
from ..errors.bad_request_error import BadRequestError
from ..errors.forbidden_error import ForbiddenError
from ..errors.internal_server_error import InternalServerError
from ..errors.not_found_error import NotFoundError
from ..errors.unauthorized_error import UnauthorizedError
from ..types.attach_webhook_result import AttachWebhookResult
from ..types.detach_webhook_result import DetachWebhookResult
from ..types.error import Error
from ..types.list_webhooks_response import ListWebhooksResponse
from ..types.webhook_event_enum import WebhookEventEnum
from ..types.webhook_result import WebhookResult
from .types.list_webhooks_request_status import ListWebhooksRequestStatus

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


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

    def get(
        self, *, identifiers: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[WebhookResult]:
        """
        Retrieve all webhook that are set up to receive events for specific URLs or phone numbers.

        Parameters
        ----------
        identifiers : typing.Sequence[str]
            List of URLs or phone numbers in E.164 format that the webhook is attached to. <br><br>
            **Limit:** 1 min

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

        Returns
        -------
        HttpResponse[WebhookResult]
            Returns all webhooks matching the search criteria. <br>

            Results are sorted by ID and duplicates are removed. This identifier is a string that always begins with the prefix `wh_`, for example: `wh_1234567890`.
        """
        _response = self._client_wrapper.httpx_client.request(
            "webhooks",
            method="POST",
            json={
                "identifiers": identifiers,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    WebhookResult,
                    parse_obj_as(
                        type_=WebhookResult,  # 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.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # 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 list(
        self,
        *,
        page_index: typing.Optional[int] = OMIT,
        page_size: typing.Optional[int] = OMIT,
        status: typing.Optional[ListWebhooksRequestStatus] = OMIT,
        endpoint: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ListWebhooksResponse]:
        """
        List all webhooks with optional filtering and pagination. Results are sorted by creation date, newest first.

        Parameters
        ----------
        page_index : typing.Optional[int]

        page_size : typing.Optional[int]

        status : typing.Optional[ListWebhooksRequestStatus]

        endpoint : typing.Optional[str]
            Filter webhooks by endpoint URL (partial match, case-insensitive).

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

        Returns
        -------
        HttpResponse[ListWebhooksResponse]
            Returns paginated list of webhooks.
        """
        _response = self._client_wrapper.httpx_client.request(
            "webhooks/list",
            method="POST",
            json={
                "pageIndex": page_index,
                "pageSize": page_size,
                "status": status,
                "endpoint": endpoint,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ListWebhooksResponse,
                    parse_obj_as(
                        type_=ListWebhooksResponse,  # 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.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # 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 attach(
        self,
        *,
        senders: typing.Sequence[str],
        webhook_id: typing.Optional[str] = OMIT,
        name: typing.Optional[str] = OMIT,
        url: typing.Optional[str] = OMIT,
        event: typing.Optional[WebhookEventEnum] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[AttachWebhookResult]:
        """
        Attach a webhook to one or more senders (phone numbers or RCS agent IDs) to receive real-time event notifications. <br>

        You can attach an existing webhook by providing its ID, or create a new webhook by specifying a name and URL. Supports bulk operations with up to 50 senders per request. <br>

        Subscriptions are additive — attaching new senders does not remove existing ones. Re-attaching the same sender updates the event type filter without creating duplicates.

        Parameters
        ----------
        senders : typing.Sequence[str]
            Array of senders to attach the webhook to. Can be phone numbers in E.164 format or RCS agent IDs.

        webhook_id : typing.Optional[str]
            Existing webhook ID (starts with `wh_`). Provide this OR `name` + `url` to create a new webhook. The webhook must be in ENABLED status. Disabled webhooks can be re-enabled from the [dashboard](https://app.pinnacle.sh/dashboard/development/webhooks).

        name : typing.Optional[str]
            Name for a new webhook (required if no `webhookId`).

        url : typing.Optional[str]
            HTTPS endpoint URL for a new webhook (required if no `webhookId`).

        event : typing.Optional[WebhookEventEnum]
            Event type filter for the subscription. Set to `null` to receive all events. <br>

            `USER.TYPING` is only supported for RCS agent senders, not phone numbers.

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

        Returns
        -------
        HttpResponse[AttachWebhookResult]
            Successfully attached webhook to the specified senders. <br>

            Senders that could not be found are returned in the `failed` array with error details.
        """
        _response = self._client_wrapper.httpx_client.request(
            "webhooks/attach",
            method="POST",
            json={
                "senders": senders,
                "webhookId": webhook_id,
                "name": name,
                "url": url,
                "event": event,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    AttachWebhookResult,
                    parse_obj_as(
                        type_=AttachWebhookResult,  # 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.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # 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 detach(
        self, *, webhook_id: str, senders: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[DetachWebhookResult]:
        """
        Detach a webhook from one or more senders (phone numbers or RCS agent IDs) to stop receiving event notifications. <br>

        The webhook itself is not deleted and remains available for use with other senders. Works regardless of webhook status. Supports bulk operations with up to 50 senders per request.

        Parameters
        ----------
        webhook_id : str
            Webhook ID to detach (starts with `wh_`). Must be a webhook owned by your team.

        senders : typing.Sequence[str]
            Array of senders to detach the webhook from. Can be phone numbers in E.164 format or RCS agent IDs.

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

        Returns
        -------
        HttpResponse[DetachWebhookResult]
            Successfully detached webhook from the specified senders. <br>

            Senders that could not be found are returned in the `failed` array with error details.
        """
        _response = self._client_wrapper.httpx_client.request(
            "webhooks/detach",
            method="POST",
            json={
                "webhookId": webhook_id,
                "senders": senders,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    DetachWebhookResult,
                    parse_obj_as(
                        type_=DetachWebhookResult,  # 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.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # 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 AsyncRawWebhooksClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def get(
        self, *, identifiers: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[WebhookResult]:
        """
        Retrieve all webhook that are set up to receive events for specific URLs or phone numbers.

        Parameters
        ----------
        identifiers : typing.Sequence[str]
            List of URLs or phone numbers in E.164 format that the webhook is attached to. <br><br>
            **Limit:** 1 min

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

        Returns
        -------
        AsyncHttpResponse[WebhookResult]
            Returns all webhooks matching the search criteria. <br>

            Results are sorted by ID and duplicates are removed. This identifier is a string that always begins with the prefix `wh_`, for example: `wh_1234567890`.
        """
        _response = await self._client_wrapper.httpx_client.request(
            "webhooks",
            method="POST",
            json={
                "identifiers": identifiers,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    WebhookResult,
                    parse_obj_as(
                        type_=WebhookResult,  # 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.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # 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 list(
        self,
        *,
        page_index: typing.Optional[int] = OMIT,
        page_size: typing.Optional[int] = OMIT,
        status: typing.Optional[ListWebhooksRequestStatus] = OMIT,
        endpoint: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ListWebhooksResponse]:
        """
        List all webhooks with optional filtering and pagination. Results are sorted by creation date, newest first.

        Parameters
        ----------
        page_index : typing.Optional[int]

        page_size : typing.Optional[int]

        status : typing.Optional[ListWebhooksRequestStatus]

        endpoint : typing.Optional[str]
            Filter webhooks by endpoint URL (partial match, case-insensitive).

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

        Returns
        -------
        AsyncHttpResponse[ListWebhooksResponse]
            Returns paginated list of webhooks.
        """
        _response = await self._client_wrapper.httpx_client.request(
            "webhooks/list",
            method="POST",
            json={
                "pageIndex": page_index,
                "pageSize": page_size,
                "status": status,
                "endpoint": endpoint,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ListWebhooksResponse,
                    parse_obj_as(
                        type_=ListWebhooksResponse,  # 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.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # 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 attach(
        self,
        *,
        senders: typing.Sequence[str],
        webhook_id: typing.Optional[str] = OMIT,
        name: typing.Optional[str] = OMIT,
        url: typing.Optional[str] = OMIT,
        event: typing.Optional[WebhookEventEnum] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[AttachWebhookResult]:
        """
        Attach a webhook to one or more senders (phone numbers or RCS agent IDs) to receive real-time event notifications. <br>

        You can attach an existing webhook by providing its ID, or create a new webhook by specifying a name and URL. Supports bulk operations with up to 50 senders per request. <br>

        Subscriptions are additive — attaching new senders does not remove existing ones. Re-attaching the same sender updates the event type filter without creating duplicates.

        Parameters
        ----------
        senders : typing.Sequence[str]
            Array of senders to attach the webhook to. Can be phone numbers in E.164 format or RCS agent IDs.

        webhook_id : typing.Optional[str]
            Existing webhook ID (starts with `wh_`). Provide this OR `name` + `url` to create a new webhook. The webhook must be in ENABLED status. Disabled webhooks can be re-enabled from the [dashboard](https://app.pinnacle.sh/dashboard/development/webhooks).

        name : typing.Optional[str]
            Name for a new webhook (required if no `webhookId`).

        url : typing.Optional[str]
            HTTPS endpoint URL for a new webhook (required if no `webhookId`).

        event : typing.Optional[WebhookEventEnum]
            Event type filter for the subscription. Set to `null` to receive all events. <br>

            `USER.TYPING` is only supported for RCS agent senders, not phone numbers.

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

        Returns
        -------
        AsyncHttpResponse[AttachWebhookResult]
            Successfully attached webhook to the specified senders. <br>

            Senders that could not be found are returned in the `failed` array with error details.
        """
        _response = await self._client_wrapper.httpx_client.request(
            "webhooks/attach",
            method="POST",
            json={
                "senders": senders,
                "webhookId": webhook_id,
                "name": name,
                "url": url,
                "event": event,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    AttachWebhookResult,
                    parse_obj_as(
                        type_=AttachWebhookResult,  # 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.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # 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 detach(
        self, *, webhook_id: str, senders: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[DetachWebhookResult]:
        """
        Detach a webhook from one or more senders (phone numbers or RCS agent IDs) to stop receiving event notifications. <br>

        The webhook itself is not deleted and remains available for use with other senders. Works regardless of webhook status. Supports bulk operations with up to 50 senders per request.

        Parameters
        ----------
        webhook_id : str
            Webhook ID to detach (starts with `wh_`). Must be a webhook owned by your team.

        senders : typing.Sequence[str]
            Array of senders to detach the webhook from. Can be phone numbers in E.164 format or RCS agent IDs.

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

        Returns
        -------
        AsyncHttpResponse[DetachWebhookResult]
            Successfully detached webhook from the specified senders. <br>

            Senders that could not be found are returned in the `failed` array with error details.
        """
        _response = await self._client_wrapper.httpx_client.request(
            "webhooks/detach",
            method="POST",
            json={
                "webhookId": webhook_id,
                "senders": senders,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    DetachWebhookResult,
                    parse_obj_as(
                        type_=DetachWebhookResult,  # 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.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # 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)
