# This file was auto-generated by Fern from our API Definition.

import datetime as dt
import typing
from json.decoder import JSONDecodeError

from ..core.api_error import ApiError
from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.datetime_utils import serialize_datetime
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 ..core.serialization import convert_and_respect_annotation_metadata
from ..errors.bad_request_error import BadRequestError
from ..errors.internal_server_error import InternalServerError
from ..errors.not_found_error import NotFoundError
from ..errors.unauthorized_error import UnauthorizedError
from ..types.campaign_enum import CampaignEnum
from ..types.conversation import Conversation
from ..types.conversation_list import ConversationList
from ..types.error import Error
from ..types.get_conversation_params import GetConversationParams
from ..types.message_list import MessageList
from ..types.sender import Sender
from ..types.successful_conversation_update import SuccessfulConversationUpdate
from .types.conversations_list_messages_request_direction import ConversationsListMessagesRequestDirection
from .types.conversations_list_messages_request_sort_order import ConversationsListMessagesRequestSortOrder
from .types.conversations_list_messages_request_status import ConversationsListMessagesRequestStatus
from .types.conversations_list_messages_request_type import ConversationsListMessagesRequestType

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


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

    def get(
        self, *, request: GetConversationParams, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[typing.Optional[Conversation]]:
        """
        Fetch a specific conversation using either its unique identifier or by matching sender and recipient details.

        Parameters
        ----------
        request : GetConversationParams

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

        Returns
        -------
        HttpResponse[typing.Optional[Conversation]]
            Returns the full conversation details, or null if not found.
        """
        _response = self._client_wrapper.httpx_client.request(
            "conversations/get",
            method="POST",
            json=convert_and_respect_annotation_metadata(
                object_=request, annotation=GetConversationParams, direction="write"
            ),
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if _response is None or not _response.text.strip():
                return HttpResponse(response=_response, data=None)
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Optional[Conversation],
                    parse_obj_as(
                        type_=typing.Optional[Conversation],  # 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 list(
        self,
        *,
        page_index: int,
        brand_id: typing.Optional[str] = OMIT,
        campaign_id: typing.Optional[str] = OMIT,
        campaign_type: typing.Optional[CampaignEnum] = OMIT,
        page_size: typing.Optional[int] = OMIT,
        receiver: typing.Optional[str] = OMIT,
        sender: typing.Optional[Sender] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ConversationList]:
        """
        Retrieves conversations by page with optional filtering based off provided parameters.

        Parameters
        ----------
        page_index : int
            Zero-based index for pagination.

        brand_id : typing.Optional[str]
            The unique identifier of the brand to filter conversations. This identifier is a string that always begins with the prefix `b_`, for example: `b_1234567890`.

        campaign_id : typing.Optional[str]
            The unique identifier of the campaign to filter conversations. This identifier is a string that begins with the prefix:
            - TOLL_FREE: `tf_` (e.g., `tf_1234567890`)
            - 10DLC: `dlc_` (e.g., `dlc_1234567890`)
            - RCS: `rcs_` (e.g., `rcs_1234567890`)

        campaign_type : typing.Optional[CampaignEnum]

        page_size : typing.Optional[int]
            Number of conversations to return per page.

        receiver : typing.Optional[str]
            Receiver's phone number in E.164 format.

        sender : typing.Optional[Sender]

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

        Returns
        -------
        HttpResponse[ConversationList]
            Returns conversations that meets your filters.
        """
        _response = self._client_wrapper.httpx_client.request(
            "conversations/list",
            method="POST",
            json={
                "brandId": brand_id,
                "campaignId": campaign_id,
                "campaignType": campaign_type,
                "pageIndex": page_index,
                "pageSize": page_size,
                "receiver": receiver,
                "sender": sender,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ConversationList,
                    parse_obj_as(
                        type_=ConversationList,  # 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 update(
        self, *, id: str, notes: str, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[SuccessfulConversationUpdate]:
        """
        Update the notes associated with a specific conversation.

        Parameters
        ----------
        id : str
            The unique identifier of the conversation to update. This identifier is a string that always begins with the prefix `conv_`, for example: `conv_1234567890`.

        notes : str
            New notes or comments for the conversation.

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

        Returns
        -------
        HttpResponse[SuccessfulConversationUpdate]
            Successfully updated the conversation.
        """
        _response = self._client_wrapper.httpx_client.request(
            "conversations/update",
            method="POST",
            json={
                "id": id,
                "notes": notes,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    SuccessfulConversationUpdate,
                    parse_obj_as(
                        type_=SuccessfulConversationUpdate,  # 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 list_messages(
        self,
        id: str,
        *,
        page_index: typing.Optional[int] = None,
        page_size: typing.Optional[int] = None,
        sort_order: typing.Optional[ConversationsListMessagesRequestSortOrder] = None,
        direction: typing.Optional[ConversationsListMessagesRequestDirection] = None,
        status: typing.Optional[ConversationsListMessagesRequestStatus] = None,
        type: typing.Optional[ConversationsListMessagesRequestType] = None,
        date_from: typing.Optional[dt.datetime] = None,
        date_to: typing.Optional[dt.datetime] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[MessageList]:
        """
        Retrieve a paginated and filtered list of messages for a specific conversation.

        Parameters
        ----------
        id : str
            Unique identifier of the conversation. This identifier is a string that always begins with the prefix `conv_`, for example: `conv_1234567890`.

        page_index : typing.Optional[int]
            Zero-based index for pagination.

        page_size : typing.Optional[int]
            Number of messages to return per page.

        sort_order : typing.Optional[ConversationsListMessagesRequestSortOrder]
            Sort order for messages. <br>

            - `asc`: Oldest messages first
            - `desc`: Newest messages first (default)

        direction : typing.Optional[ConversationsListMessagesRequestDirection]
            Filter messages by direction. <br>

            - `INBOUND`: Messages received from contacts
            - `OUTBOUND`: Messages sent to contacts

        status : typing.Optional[ConversationsListMessagesRequestStatus]
            Filter messages by delivery status.

        type : typing.Optional[ConversationsListMessagesRequestType]
            Filter messages by protocol type.

        date_from : typing.Optional[dt.datetime]
            Filter messages sent on or after this date (ISO 8601 format).

        date_to : typing.Optional[dt.datetime]
            Filter messages sent on or before this date (ISO 8601 format).

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

        Returns
        -------
        HttpResponse[MessageList]
            Returns a paginated list of messages in the conversation.
        """
        _response = self._client_wrapper.httpx_client.request(
            f"conversations/{jsonable_encoder(id)}/messages",
            method="POST",
            params={
                "pageIndex": page_index,
                "pageSize": page_size,
                "sortOrder": sort_order,
                "direction": direction,
                "status": status,
                "type": type,
                "dateFrom": serialize_datetime(date_from) if date_from is not None else None,
                "dateTo": serialize_datetime(date_to) if date_to is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    MessageList,
                    parse_obj_as(
                        type_=MessageList,  # 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 AsyncRawConversationsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def get(
        self, *, request: GetConversationParams, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[typing.Optional[Conversation]]:
        """
        Fetch a specific conversation using either its unique identifier or by matching sender and recipient details.

        Parameters
        ----------
        request : GetConversationParams

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

        Returns
        -------
        AsyncHttpResponse[typing.Optional[Conversation]]
            Returns the full conversation details, or null if not found.
        """
        _response = await self._client_wrapper.httpx_client.request(
            "conversations/get",
            method="POST",
            json=convert_and_respect_annotation_metadata(
                object_=request, annotation=GetConversationParams, direction="write"
            ),
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if _response is None or not _response.text.strip():
                return AsyncHttpResponse(response=_response, data=None)
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Optional[Conversation],
                    parse_obj_as(
                        type_=typing.Optional[Conversation],  # 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 list(
        self,
        *,
        page_index: int,
        brand_id: typing.Optional[str] = OMIT,
        campaign_id: typing.Optional[str] = OMIT,
        campaign_type: typing.Optional[CampaignEnum] = OMIT,
        page_size: typing.Optional[int] = OMIT,
        receiver: typing.Optional[str] = OMIT,
        sender: typing.Optional[Sender] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ConversationList]:
        """
        Retrieves conversations by page with optional filtering based off provided parameters.

        Parameters
        ----------
        page_index : int
            Zero-based index for pagination.

        brand_id : typing.Optional[str]
            The unique identifier of the brand to filter conversations. This identifier is a string that always begins with the prefix `b_`, for example: `b_1234567890`.

        campaign_id : typing.Optional[str]
            The unique identifier of the campaign to filter conversations. This identifier is a string that begins with the prefix:
            - TOLL_FREE: `tf_` (e.g., `tf_1234567890`)
            - 10DLC: `dlc_` (e.g., `dlc_1234567890`)
            - RCS: `rcs_` (e.g., `rcs_1234567890`)

        campaign_type : typing.Optional[CampaignEnum]

        page_size : typing.Optional[int]
            Number of conversations to return per page.

        receiver : typing.Optional[str]
            Receiver's phone number in E.164 format.

        sender : typing.Optional[Sender]

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

        Returns
        -------
        AsyncHttpResponse[ConversationList]
            Returns conversations that meets your filters.
        """
        _response = await self._client_wrapper.httpx_client.request(
            "conversations/list",
            method="POST",
            json={
                "brandId": brand_id,
                "campaignId": campaign_id,
                "campaignType": campaign_type,
                "pageIndex": page_index,
                "pageSize": page_size,
                "receiver": receiver,
                "sender": sender,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ConversationList,
                    parse_obj_as(
                        type_=ConversationList,  # 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 update(
        self, *, id: str, notes: str, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[SuccessfulConversationUpdate]:
        """
        Update the notes associated with a specific conversation.

        Parameters
        ----------
        id : str
            The unique identifier of the conversation to update. This identifier is a string that always begins with the prefix `conv_`, for example: `conv_1234567890`.

        notes : str
            New notes or comments for the conversation.

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

        Returns
        -------
        AsyncHttpResponse[SuccessfulConversationUpdate]
            Successfully updated the conversation.
        """
        _response = await self._client_wrapper.httpx_client.request(
            "conversations/update",
            method="POST",
            json={
                "id": id,
                "notes": notes,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    SuccessfulConversationUpdate,
                    parse_obj_as(
                        type_=SuccessfulConversationUpdate,  # 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 list_messages(
        self,
        id: str,
        *,
        page_index: typing.Optional[int] = None,
        page_size: typing.Optional[int] = None,
        sort_order: typing.Optional[ConversationsListMessagesRequestSortOrder] = None,
        direction: typing.Optional[ConversationsListMessagesRequestDirection] = None,
        status: typing.Optional[ConversationsListMessagesRequestStatus] = None,
        type: typing.Optional[ConversationsListMessagesRequestType] = None,
        date_from: typing.Optional[dt.datetime] = None,
        date_to: typing.Optional[dt.datetime] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[MessageList]:
        """
        Retrieve a paginated and filtered list of messages for a specific conversation.

        Parameters
        ----------
        id : str
            Unique identifier of the conversation. This identifier is a string that always begins with the prefix `conv_`, for example: `conv_1234567890`.

        page_index : typing.Optional[int]
            Zero-based index for pagination.

        page_size : typing.Optional[int]
            Number of messages to return per page.

        sort_order : typing.Optional[ConversationsListMessagesRequestSortOrder]
            Sort order for messages. <br>

            - `asc`: Oldest messages first
            - `desc`: Newest messages first (default)

        direction : typing.Optional[ConversationsListMessagesRequestDirection]
            Filter messages by direction. <br>

            - `INBOUND`: Messages received from contacts
            - `OUTBOUND`: Messages sent to contacts

        status : typing.Optional[ConversationsListMessagesRequestStatus]
            Filter messages by delivery status.

        type : typing.Optional[ConversationsListMessagesRequestType]
            Filter messages by protocol type.

        date_from : typing.Optional[dt.datetime]
            Filter messages sent on or after this date (ISO 8601 format).

        date_to : typing.Optional[dt.datetime]
            Filter messages sent on or before this date (ISO 8601 format).

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

        Returns
        -------
        AsyncHttpResponse[MessageList]
            Returns a paginated list of messages in the conversation.
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"conversations/{jsonable_encoder(id)}/messages",
            method="POST",
            params={
                "pageIndex": page_index,
                "pageSize": page_size,
                "sortOrder": sort_order,
                "direction": direction,
                "status": status,
                "type": type,
                "dateFrom": serialize_datetime(date_from) if date_from is not None else None,
                "dateTo": serialize_datetime(date_to) if date_to is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    MessageList,
                    parse_obj_as(
                        type_=MessageList,  # 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)
