# 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.pagination import AsyncPager, SyncPager
from ..core.request_options import RequestOptions
from ..core.serialization import convert_and_respect_annotation_metadata
from ..core.unchecked_base_model import construct_type
from ..errors.bad_request_error import BadRequestError
from ..errors.forbidden_error import ForbiddenError
from ..errors.not_found_error import NotFoundError
from ..errors.unauthorized_error import UnauthorizedError
from ..errors.unprocessable_entity_error import UnprocessableEntityError
from ..messages.types.message import Message
from ..tickets.types.ticket import Ticket
from ..types.conversation_deleted import ConversationDeleted
from ..types.conversation_list import ConversationList
from ..types.custom_attributes import CustomAttributes
from ..types.error import Error
from ..types.redact_conversation_request import RedactConversationRequest
from ..types.reply_conversation_request import ReplyConversationRequest
from ..types.search_request_query import SearchRequestQuery
from ..types.starting_after_paging import StartingAfterPaging
from ..types.ticket_request_custom_attributes import TicketRequestCustomAttributes
from .types.attach_contact_to_conversation_request_customer import AttachContactToConversationRequestCustomer
from .types.conversation import Conversation
from .types.conversations_manage_request_body import ConversationsManageRequestBody
from .types.create_conversation_request_from import CreateConversationRequestFrom

# 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 list(
        self,
        *,
        per_page: typing.Optional[int] = None,
        starting_after: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> SyncPager[Conversation, ConversationList]:
        """
        You can fetch a list of all conversations.

        You can optionally request the result page size and the cursor to start after to fetch the result.
        {% admonition type="warning" name="Pagination" %}
          You can use pagination to limit the number of results returned. The default is `20` results per page.
          See the [pagination section](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#pagination-for-list-apis) for more details on how to use the `starting_after` param.
        {% /admonition %}

        Parameters
        ----------
        per_page : typing.Optional[int]
            How many results per page

        starting_after : typing.Optional[str]
            String used to get the next page of conversations.

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

        Returns
        -------
        SyncPager[Conversation, ConversationList]
            successful
        """
        _response = self._client_wrapper.httpx_client.request(
            "conversations",
            method="GET",
            params={
                "per_page": per_page,
                "starting_after": starting_after,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ConversationList,
                    construct_type(
                        type_=ConversationList,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _items = _parsed_response.conversations
                _has_next = False
                _get_next = None
                if _parsed_response.pages is not None and _parsed_response.pages.next is not None:
                    _parsed_next = _parsed_response.pages.next.starting_after
                    _has_next = _parsed_next is not None and _parsed_next != ""
                    _get_next = lambda: self.list(
                        per_page=per_page,
                        starting_after=_parsed_next,
                        request_options=request_options,
                    )
                return SyncPager(has_next=_has_next, items=_items, get_next=_get_next, response=_parsed_response)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            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 create(
        self,
        *,
        from_: CreateConversationRequestFrom,
        body: str,
        created_at: typing.Optional[int] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[Message]:
        """
        You can create a conversation that has been initiated by a contact (ie. user or lead).
        The conversation can be an in-app message only.

        {% admonition type="info" name="Sending for visitors" %}
        You can also send a message from a visitor by specifying their `user_id` or `id` value in the `from` field, along with a `type` field value of `contact`.
        This visitor will be automatically converted to a contact with a lead role once the conversation is created.
        {% /admonition %}

        This will return the Message model that has been created.

        Parameters
        ----------
        from_ : CreateConversationRequestFrom

        body : str
            The content of the message. HTML is not supported.

        created_at : typing.Optional[int]
            The time the conversation was created as a UTC Unix timestamp. If not provided, the current time will be used. This field is only recommneded for migrating past conversations from another source into Intercom.

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

        Returns
        -------
        HttpResponse[Message]
            conversation created
        """
        _response = self._client_wrapper.httpx_client.request(
            "conversations",
            method="POST",
            json={
                "from": convert_and_respect_annotation_metadata(
                    object_=from_, annotation=CreateConversationRequestFrom, direction="write"
                ),
                "body": body,
                "created_at": created_at,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Message,
                    construct_type(
                        type_=Message,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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 find(
        self,
        conversation_id: str,
        *,
        display_as: typing.Optional[str] = None,
        include_translations: typing.Optional[bool] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[Conversation]:
        """

        You can fetch the details of a single conversation.

        This will return a single Conversation model with all its conversation parts.

        {% admonition type="warning" name="Hard limit of 500 parts" %}
        The maximum number of conversation parts that can be returned via the API is 500. If you have more than that we will return the 500 most recent conversation parts.
        {% /admonition %}

        For AI agent conversation metadata, please note that you need to have the agent enabled in your workspace, which is a [paid feature](https://www.intercom.com/help/en/articles/8205718-fin-resolutions#h_97f8c2e671).

        Parameters
        ----------
        conversation_id : str
            The id of the conversation to target

        display_as : typing.Optional[str]
            Set to plaintext to retrieve conversation messages in plain text.

        include_translations : typing.Optional[bool]
            If set to true, conversation parts will be translated to the detected language of the conversation.

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

        Returns
        -------
        HttpResponse[Conversation]
            conversation found
        """
        _response = self._client_wrapper.httpx_client.request(
            f"conversations/{jsonable_encoder(conversation_id)}",
            method="GET",
            params={
                "display_as": display_as,
                "include_translations": include_translations,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Conversation,
                    construct_type(
                        type_=Conversation,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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(
        self,
        conversation_id: str,
        *,
        display_as: typing.Optional[str] = None,
        read: typing.Optional[bool] = OMIT,
        title: typing.Optional[str] = OMIT,
        custom_attributes: typing.Optional[CustomAttributes] = OMIT,
        company_id: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[Conversation]:
        """

        You can update an existing conversation.

        {% admonition type="info" name="Replying and other actions" %}
        If you want to reply to a coveration or take an action such as assign, unassign, open, close or snooze, take a look at the reply and manage endpoints.
        {% /admonition %}

        {% admonition type="info" %}
          This endpoint handles both **conversation updates** and **custom object associations**.

          See _`update a conversation with an association to a custom object instance`_ in the request/response examples to see the custom object association format.
        {% /admonition %}

        Parameters
        ----------
        conversation_id : str
            The id of the conversation to target

        display_as : typing.Optional[str]
            Set to plaintext to retrieve conversation messages in plain text.

        read : typing.Optional[bool]
            Mark a conversation as read within Intercom.

        title : typing.Optional[str]
            The title given to the conversation

        custom_attributes : typing.Optional[CustomAttributes]

        company_id : typing.Optional[str]
            The ID of the company that the conversation is associated with. The unique identifier for the company which is given by Intercom. Set to nil to remove company.

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

        Returns
        -------
        HttpResponse[Conversation]
            update a conversation with an association to a custom object instance
        """
        _response = self._client_wrapper.httpx_client.request(
            f"conversations/{jsonable_encoder(conversation_id)}",
            method="PUT",
            params={
                "display_as": display_as,
            },
            json={
                "read": read,
                "title": title,
                "custom_attributes": convert_and_respect_annotation_metadata(
                    object_=custom_attributes, annotation=CustomAttributes, direction="write"
                ),
                "company_id": company_id,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Conversation,
                    construct_type(
                        type_=Conversation,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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_conversation(
        self, conversation_id: int, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[ConversationDeleted]:
        """
        You can delete a single conversation.

        Parameters
        ----------
        conversation_id : int
            id

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

        Returns
        -------
        HttpResponse[ConversationDeleted]
            successful
        """
        _response = self._client_wrapper.httpx_client.request(
            f"conversations/{jsonable_encoder(conversation_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ConversationDeleted,
                    construct_type(
                        type_=ConversationDeleted,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            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 search(
        self,
        *,
        query: SearchRequestQuery,
        pagination: typing.Optional[StartingAfterPaging] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> SyncPager[Conversation, ConversationList]:
        """
        You can search for multiple conversations by the value of their attributes in order to fetch exactly which ones you want.

        To search for conversations, you need to send a `POST` request to `https://api.intercom.io/conversations/search`.

        This will accept a query object in the body which will define your filters in order to search for conversations.
        {% admonition type="warning" name="Optimizing search queries" %}
          Search queries can be complex, so optimizing them can help the performance of your search.
          Use the `AND` and `OR` operators to combine multiple filters to get the exact results you need and utilize
          pagination to limit the number of results returned. The default is `20` results per page and maximum is `150`.
          See the [pagination section](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#example-search-conversations-request) for more details on how to use the `starting_after` param.
        {% /admonition %}

        ### Nesting & Limitations

        You can nest these filters in order to get even more granular insights that pinpoint exactly what you need. Example: (1 OR 2) AND (3 OR 4).
        There are some limitations to the amount of multiple's there can be:
        - There's a limit of max 2 nested filters
        - There's a limit of max 15 filters for each AND or OR group

        ### Accepted Fields

        Most keys listed in the conversation model are searchable, whether writeable or not. The value you search for has to match the accepted type, otherwise the query will fail (ie. as `created_at` accepts a date, the `value` cannot be a string such as `"foorbar"`).
        The `source.body` field is unique as the search will not be performed against the entire value, but instead against every element of the value separately. For example, when searching for a conversation with a `"I need support"` body - the query should contain a `=` operator with the value `"support"` for such conversation to be returned. A query with a `=` operator and a `"need support"` value will not yield a result.

        | Field                                     | Type                                                                                                                                                   |
        | :---------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- |
        | id                                        | String                                                                                                                                                 |
        | created_at                                | Date (UNIX timestamp)                                                                                                                                  |
        | updated_at                                | Date (UNIX timestamp)                                                                                                                                  |
        | source.type                               | String<br>Accepted fields are `conversation`, `email`, `facebook`, `instagram`, `phone_call`, `phone_switch`, `push`, `sms`, `twitter` and `whatsapp`. |
        | source.id                                 | String                                                                                                                                                 |
        | source.delivered_as                       | String                                                                                                                                                 |
        | source.subject                            | String                                                                                                                                                 |
        | source.body                               | String                                                                                                                                                 |
        | source.author.id                          | String                                                                                                                                                 |
        | source.author.type                        | String                                                                                                                                                 |
        | source.author.name                        | String                                                                                                                                                 |
        | source.author.email                       | String                                                                                                                                                 |
        | source.url                                | String                                                                                                                                                 |
        | contact_ids                               | String                                                                                                                                                 |
        | teammate_ids                              | String                                                                                                                                                 |
        | admin_assignee_id                         | String                                                                                                                                                 |
        | team_assignee_id                          | String                                                                                                                                                 |
        | channel_initiated                         | String                                                                                                                                                 |
        | open                                      | Boolean                                                                                                                                                |
        | read                                      | Boolean                                                                                                                                                |
        | state                                     | String                                                                                                                                                 |
        | waiting_since                             | Date (UNIX timestamp)                                                                                                                                  |
        | snoozed_until                             | Date (UNIX timestamp)                                                                                                                                  |
        | tag_ids                                   | String                                                                                                                                                 |
        | priority                                  | String                                                                                                                                                 |
        | statistics.time_to_assignment             | Integer                                                                                                                                                |
        | statistics.time_to_admin_reply            | Integer                                                                                                                                                |
        | statistics.time_to_first_close            | Integer                                                                                                                                                |
        | statistics.time_to_last_close             | Integer                                                                                                                                                |
        | statistics.median_time_to_reply           | Integer                                                                                                                                                |
        | statistics.first_contact_reply_at         | Date (UNIX timestamp)                                                                                                                                  |
        | statistics.first_assignment_at            | Date (UNIX timestamp)                                                                                                                                  |
        | statistics.first_admin_reply_at           | Date (UNIX timestamp)                                                                                                                                  |
        | statistics.first_close_at                 | Date (UNIX timestamp)                                                                                                                                  |
        | statistics.last_assignment_at             | Date (UNIX timestamp)                                                                                                                                  |
        | statistics.last_assignment_admin_reply_at | Date (UNIX timestamp)                                                                                                                                  |
        | statistics.last_contact_reply_at          | Date (UNIX timestamp)                                                                                                                                  |
        | statistics.last_admin_reply_at            | Date (UNIX timestamp)                                                                                                                                  |
        | statistics.last_close_at                  | Date (UNIX timestamp)                                                                                                                                  |
        | statistics.last_closed_by_id              | String                                                                                                                                                 |
        | statistics.count_reopens                  | Integer                                                                                                                                                |
        | statistics.count_assignments              | Integer                                                                                                                                                |
        | statistics.count_conversation_parts       | Integer                                                                                                                                                |
        | conversation_rating.requested_at          | Date (UNIX timestamp)                                                                                                                                  |
        | conversation_rating.replied_at            | Date (UNIX timestamp)                                                                                                                                  |
        | conversation_rating.score                 | Integer                                                                                                                                                |
        | conversation_rating.remark                | String                                                                                                                                                 |
        | conversation_rating.contact_id            | String                                                                                                                                                 |
        | conversation_rating.admin_d               | String                                                                                                                                                 |
        | ai_agent_participated                     | Boolean                                                                                                                                                |
        | ai_agent.resolution_state                 | String                                                                                                                                                 |
        | ai_agent.last_answer_type                 | String                                                                                                                                                 |
        | ai_agent.rating                           | Integer                                                                                                                                                |
        | ai_agent.rating_remark                    | String                                                                                                                                                 |
        | ai_agent.source_type                      | String                                                                                                                                                 |
        | ai_agent.source_title                     | String                                                                                                                                                 |

        ### Accepted Operators

        The table below shows the operators you can use to define how you want to search for the value.  The operator should be put in as a string (`"="`). The operator has to be compatible with the field's type  (eg. you cannot search with `>` for a given string value as it's only compatible for integer's and dates).

        | Operator | Valid Types                    | Description                                                  |
        | :------- | :----------------------------- | :----------------------------------------------------------- |
        | =        | All                            | Equals                                                       |
        | !=       | All                            | Doesn't Equal                                                |
        | IN       | All                            | In  Shortcut for `OR` queries  Values most be in Array       |
        | NIN      | All                            | Not In  Shortcut for `OR !` queries  Values must be in Array |
        | >        | Integer  Date (UNIX Timestamp) | Greater (or equal) than                                      |
        | <       | Integer  Date (UNIX Timestamp) | Lower (or equal) than                                        |
        | ~        | String                         | Contains                                                     |
        | !~       | String                         | Doesn't Contain                                              |
        | ^        | String                         | Starts With                                                  |
        | $        | String                         | Ends With                                                    |

        Parameters
        ----------
        query : SearchRequestQuery

        pagination : typing.Optional[StartingAfterPaging]

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

        Returns
        -------
        SyncPager[Conversation, ConversationList]
            successful
        """
        _response = self._client_wrapper.httpx_client.request(
            "conversations/search",
            method="POST",
            json={
                "query": convert_and_respect_annotation_metadata(
                    object_=query, annotation=SearchRequestQuery, direction="write"
                ),
                "pagination": convert_and_respect_annotation_metadata(
                    object_=pagination, annotation=StartingAfterPaging, direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ConversationList,
                    construct_type(
                        type_=ConversationList,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _items = _parsed_response.conversations
                _has_next = False
                _get_next = None
                if _parsed_response.pages is not None and _parsed_response.pages.next is not None:
                    _parsed_next = _parsed_response.pages.next.starting_after
                    _has_next = _parsed_next is not None and _parsed_next != ""
                    _get_next = lambda: self.search(
                        query=query,
                        pagination=pagination,
                        request_options=request_options,
                    )
                return SyncPager(has_next=_has_next, items=_items, get_next=_get_next, response=_parsed_response)
            _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 reply(
        self,
        conversation_id: str,
        *,
        request: ReplyConversationRequest,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[Conversation]:
        """
        You can reply to a conversation with a message from an admin or on behalf of a contact, or with a note for admins.

        Parameters
        ----------
        conversation_id : str
            The Intercom provisioned identifier for the conversation or the string "last" to reply to the last part of the conversation

        request : ReplyConversationRequest

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

        Returns
        -------
        HttpResponse[Conversation]
            User last conversation reply
        """
        _response = self._client_wrapper.httpx_client.request(
            f"conversations/{jsonable_encoder(conversation_id)}/reply",
            method="POST",
            json=convert_and_respect_annotation_metadata(
                object_=request, annotation=ReplyConversationRequest, direction="write"
            ),
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Conversation,
                    construct_type(
                        type_=Conversation,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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 manage(
        self,
        conversation_id: str,
        *,
        request: ConversationsManageRequestBody,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[Conversation]:
        """
        For managing conversations you can:
        - Close a conversation
        - Snooze a conversation to reopen on a future date
        - Open a conversation which is `snoozed` or `closed`
        - Assign a conversation to an admin and/or team.

        Parameters
        ----------
        conversation_id : str
            The identifier for the conversation as given by Intercom.

        request : ConversationsManageRequestBody

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

        Returns
        -------
        HttpResponse[Conversation]
            Assign a conversation
        """
        _response = self._client_wrapper.httpx_client.request(
            f"conversations/{jsonable_encoder(conversation_id)}/parts",
            method="POST",
            json=convert_and_respect_annotation_metadata(
                object_=request, annotation=ConversationsManageRequestBody, direction="write"
            ),
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Conversation,
                    construct_type(
                        type_=Conversation,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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 attach_contact_as_admin(
        self,
        conversation_id: str,
        *,
        admin_id: typing.Optional[str] = OMIT,
        customer: typing.Optional[AttachContactToConversationRequestCustomer] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[Conversation]:
        """
        You can add participants who are contacts to a conversation, on behalf of either another contact or an admin.

        {% admonition type="warning" name="Contacts without an email" %}
        If you add a contact via the email parameter and there is no user/lead found on that workspace with he given email, then we will create a new contact with `role` set to `lead`.
        {% /admonition %}

        Parameters
        ----------
        conversation_id : str
            The identifier for the conversation as given by Intercom.

        admin_id : typing.Optional[str]
            The `id` of the admin who is adding the new participant.

        customer : typing.Optional[AttachContactToConversationRequestCustomer]

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

        Returns
        -------
        HttpResponse[Conversation]
            Attach a contact to a conversation
        """
        _response = self._client_wrapper.httpx_client.request(
            f"conversations/{jsonable_encoder(conversation_id)}/customers",
            method="POST",
            json={
                "admin_id": admin_id,
                "customer": convert_and_respect_annotation_metadata(
                    object_=customer, annotation=AttachContactToConversationRequestCustomer, direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Conversation,
                    construct_type(
                        type_=Conversation,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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 detach_contact_as_admin(
        self,
        conversation_id: str,
        contact_id: str,
        *,
        admin_id: str,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[Conversation]:
        """
        You can add participants who are contacts to a conversation, on behalf of either another contact or an admin.

        {% admonition type="warning" name="Contacts without an email" %}
        If you add a contact via the email parameter and there is no user/lead found on that workspace with he given email, then we will create a new contact with `role` set to `lead`.
        {% /admonition %}

        Parameters
        ----------
        conversation_id : str
            The identifier for the conversation as given by Intercom.

        contact_id : str
            The identifier for the contact as given by Intercom.

        admin_id : str
            The `id` of the admin who is performing the action.

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

        Returns
        -------
        HttpResponse[Conversation]
            Detach a contact from a group conversation
        """
        _response = self._client_wrapper.httpx_client.request(
            f"conversations/{jsonable_encoder(conversation_id)}/customers/{jsonable_encoder(contact_id)}",
            method="DELETE",
            json={
                "admin_id": admin_id,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Conversation,
                    construct_type(
                        type_=Conversation,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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 redact_conversation_part(
        self, *, request: RedactConversationRequest, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[Conversation]:
        """
        You can redact a conversation part or the source message of a conversation (as seen in the source object).

        {% admonition type="info" name="Redacting parts and messages" %}
        If you are redacting a conversation part, it must have a `body`. If you are redacting a source message, it must have been created by a contact. We will return a `conversation_part_not_redactable` error if these criteria are not met.
        {% /admonition %}

        Parameters
        ----------
        request : RedactConversationRequest

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

        Returns
        -------
        HttpResponse[Conversation]
            Redact a conversation part
        """
        _response = self._client_wrapper.httpx_client.request(
            "conversations/redact",
            method="POST",
            json=convert_and_respect_annotation_metadata(
                object_=request, annotation=RedactConversationRequest, direction="write"
            ),
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Conversation,
                    construct_type(
                        type_=Conversation,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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 convert_to_ticket(
        self,
        conversation_id: int,
        *,
        ticket_type_id: str,
        attributes: typing.Optional[TicketRequestCustomAttributes] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[typing.Optional[Ticket]]:
        """
        You can convert a conversation to a ticket.

        Parameters
        ----------
        conversation_id : int
            The id of the conversation to target

        ticket_type_id : str
            The ID of the type of ticket you want to convert the conversation to

        attributes : typing.Optional[TicketRequestCustomAttributes]

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

        Returns
        -------
        HttpResponse[typing.Optional[Ticket]]
            successful
        """
        _response = self._client_wrapper.httpx_client.request(
            f"conversations/{jsonable_encoder(conversation_id)}/convert",
            method="POST",
            json={
                "ticket_type_id": ticket_type_id,
                "attributes": attributes,
            },
            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[Ticket],
                    construct_type(
                        type_=typing.Optional[Ticket],  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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 run_assignment_rules(
        self, conversation_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[Conversation]:
        """
        {% admonition type="danger" name="Deprecation of Run Assignment Rules" %}
        Run assignment rules is now deprecated in version 2.12 and future versions and will be permanently removed on December 31, 2026. After this date, any requests made to this endpoint will fail.
        {% /admonition %}
        You can let a conversation be automatically assigned following assignment rules.
        {% admonition type="warning" name="When using workflows" %}
        It is not possible to use this endpoint with Workflows.
        {% /admonition %}

        Parameters
        ----------
        conversation_id : str
            The identifier for the conversation as given by Intercom.

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

        Returns
        -------
        HttpResponse[Conversation]
            Assign a conversation using assignment rules
        """
        _response = self._client_wrapper.httpx_client.request(
            f"conversations/{jsonable_encoder(conversation_id)}/run_assignment_rules",
            method="POST",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Conversation,
                    construct_type(
                        type_=Conversation,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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 AsyncRawConversationsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def list(
        self,
        *,
        per_page: typing.Optional[int] = None,
        starting_after: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncPager[Conversation, ConversationList]:
        """
        You can fetch a list of all conversations.

        You can optionally request the result page size and the cursor to start after to fetch the result.
        {% admonition type="warning" name="Pagination" %}
          You can use pagination to limit the number of results returned. The default is `20` results per page.
          See the [pagination section](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#pagination-for-list-apis) for more details on how to use the `starting_after` param.
        {% /admonition %}

        Parameters
        ----------
        per_page : typing.Optional[int]
            How many results per page

        starting_after : typing.Optional[str]
            String used to get the next page of conversations.

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

        Returns
        -------
        AsyncPager[Conversation, ConversationList]
            successful
        """
        _response = await self._client_wrapper.httpx_client.request(
            "conversations",
            method="GET",
            params={
                "per_page": per_page,
                "starting_after": starting_after,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ConversationList,
                    construct_type(
                        type_=ConversationList,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _items = _parsed_response.conversations
                _has_next = False
                _get_next = None
                if _parsed_response.pages is not None and _parsed_response.pages.next is not None:
                    _parsed_next = _parsed_response.pages.next.starting_after
                    _has_next = _parsed_next is not None and _parsed_next != ""

                    async def _get_next():
                        return await self.list(
                            per_page=per_page,
                            starting_after=_parsed_next,
                            request_options=request_options,
                        )

                return AsyncPager(has_next=_has_next, items=_items, get_next=_get_next, response=_parsed_response)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            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 create(
        self,
        *,
        from_: CreateConversationRequestFrom,
        body: str,
        created_at: typing.Optional[int] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[Message]:
        """
        You can create a conversation that has been initiated by a contact (ie. user or lead).
        The conversation can be an in-app message only.

        {% admonition type="info" name="Sending for visitors" %}
        You can also send a message from a visitor by specifying their `user_id` or `id` value in the `from` field, along with a `type` field value of `contact`.
        This visitor will be automatically converted to a contact with a lead role once the conversation is created.
        {% /admonition %}

        This will return the Message model that has been created.

        Parameters
        ----------
        from_ : CreateConversationRequestFrom

        body : str
            The content of the message. HTML is not supported.

        created_at : typing.Optional[int]
            The time the conversation was created as a UTC Unix timestamp. If not provided, the current time will be used. This field is only recommneded for migrating past conversations from another source into Intercom.

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

        Returns
        -------
        AsyncHttpResponse[Message]
            conversation created
        """
        _response = await self._client_wrapper.httpx_client.request(
            "conversations",
            method="POST",
            json={
                "from": convert_and_respect_annotation_metadata(
                    object_=from_, annotation=CreateConversationRequestFrom, direction="write"
                ),
                "body": body,
                "created_at": created_at,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Message,
                    construct_type(
                        type_=Message,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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 find(
        self,
        conversation_id: str,
        *,
        display_as: typing.Optional[str] = None,
        include_translations: typing.Optional[bool] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[Conversation]:
        """

        You can fetch the details of a single conversation.

        This will return a single Conversation model with all its conversation parts.

        {% admonition type="warning" name="Hard limit of 500 parts" %}
        The maximum number of conversation parts that can be returned via the API is 500. If you have more than that we will return the 500 most recent conversation parts.
        {% /admonition %}

        For AI agent conversation metadata, please note that you need to have the agent enabled in your workspace, which is a [paid feature](https://www.intercom.com/help/en/articles/8205718-fin-resolutions#h_97f8c2e671).

        Parameters
        ----------
        conversation_id : str
            The id of the conversation to target

        display_as : typing.Optional[str]
            Set to plaintext to retrieve conversation messages in plain text.

        include_translations : typing.Optional[bool]
            If set to true, conversation parts will be translated to the detected language of the conversation.

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

        Returns
        -------
        AsyncHttpResponse[Conversation]
            conversation found
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"conversations/{jsonable_encoder(conversation_id)}",
            method="GET",
            params={
                "display_as": display_as,
                "include_translations": include_translations,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Conversation,
                    construct_type(
                        type_=Conversation,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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(
        self,
        conversation_id: str,
        *,
        display_as: typing.Optional[str] = None,
        read: typing.Optional[bool] = OMIT,
        title: typing.Optional[str] = OMIT,
        custom_attributes: typing.Optional[CustomAttributes] = OMIT,
        company_id: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[Conversation]:
        """

        You can update an existing conversation.

        {% admonition type="info" name="Replying and other actions" %}
        If you want to reply to a coveration or take an action such as assign, unassign, open, close or snooze, take a look at the reply and manage endpoints.
        {% /admonition %}

        {% admonition type="info" %}
          This endpoint handles both **conversation updates** and **custom object associations**.

          See _`update a conversation with an association to a custom object instance`_ in the request/response examples to see the custom object association format.
        {% /admonition %}

        Parameters
        ----------
        conversation_id : str
            The id of the conversation to target

        display_as : typing.Optional[str]
            Set to plaintext to retrieve conversation messages in plain text.

        read : typing.Optional[bool]
            Mark a conversation as read within Intercom.

        title : typing.Optional[str]
            The title given to the conversation

        custom_attributes : typing.Optional[CustomAttributes]

        company_id : typing.Optional[str]
            The ID of the company that the conversation is associated with. The unique identifier for the company which is given by Intercom. Set to nil to remove company.

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

        Returns
        -------
        AsyncHttpResponse[Conversation]
            update a conversation with an association to a custom object instance
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"conversations/{jsonable_encoder(conversation_id)}",
            method="PUT",
            params={
                "display_as": display_as,
            },
            json={
                "read": read,
                "title": title,
                "custom_attributes": convert_and_respect_annotation_metadata(
                    object_=custom_attributes, annotation=CustomAttributes, direction="write"
                ),
                "company_id": company_id,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Conversation,
                    construct_type(
                        type_=Conversation,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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_conversation(
        self, conversation_id: int, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[ConversationDeleted]:
        """
        You can delete a single conversation.

        Parameters
        ----------
        conversation_id : int
            id

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

        Returns
        -------
        AsyncHttpResponse[ConversationDeleted]
            successful
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"conversations/{jsonable_encoder(conversation_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ConversationDeleted,
                    construct_type(
                        type_=ConversationDeleted,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            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 search(
        self,
        *,
        query: SearchRequestQuery,
        pagination: typing.Optional[StartingAfterPaging] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncPager[Conversation, ConversationList]:
        """
        You can search for multiple conversations by the value of their attributes in order to fetch exactly which ones you want.

        To search for conversations, you need to send a `POST` request to `https://api.intercom.io/conversations/search`.

        This will accept a query object in the body which will define your filters in order to search for conversations.
        {% admonition type="warning" name="Optimizing search queries" %}
          Search queries can be complex, so optimizing them can help the performance of your search.
          Use the `AND` and `OR` operators to combine multiple filters to get the exact results you need and utilize
          pagination to limit the number of results returned. The default is `20` results per page and maximum is `150`.
          See the [pagination section](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#example-search-conversations-request) for more details on how to use the `starting_after` param.
        {% /admonition %}

        ### Nesting & Limitations

        You can nest these filters in order to get even more granular insights that pinpoint exactly what you need. Example: (1 OR 2) AND (3 OR 4).
        There are some limitations to the amount of multiple's there can be:
        - There's a limit of max 2 nested filters
        - There's a limit of max 15 filters for each AND or OR group

        ### Accepted Fields

        Most keys listed in the conversation model are searchable, whether writeable or not. The value you search for has to match the accepted type, otherwise the query will fail (ie. as `created_at` accepts a date, the `value` cannot be a string such as `"foorbar"`).
        The `source.body` field is unique as the search will not be performed against the entire value, but instead against every element of the value separately. For example, when searching for a conversation with a `"I need support"` body - the query should contain a `=` operator with the value `"support"` for such conversation to be returned. A query with a `=` operator and a `"need support"` value will not yield a result.

        | Field                                     | Type                                                                                                                                                   |
        | :---------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- |
        | id                                        | String                                                                                                                                                 |
        | created_at                                | Date (UNIX timestamp)                                                                                                                                  |
        | updated_at                                | Date (UNIX timestamp)                                                                                                                                  |
        | source.type                               | String<br>Accepted fields are `conversation`, `email`, `facebook`, `instagram`, `phone_call`, `phone_switch`, `push`, `sms`, `twitter` and `whatsapp`. |
        | source.id                                 | String                                                                                                                                                 |
        | source.delivered_as                       | String                                                                                                                                                 |
        | source.subject                            | String                                                                                                                                                 |
        | source.body                               | String                                                                                                                                                 |
        | source.author.id                          | String                                                                                                                                                 |
        | source.author.type                        | String                                                                                                                                                 |
        | source.author.name                        | String                                                                                                                                                 |
        | source.author.email                       | String                                                                                                                                                 |
        | source.url                                | String                                                                                                                                                 |
        | contact_ids                               | String                                                                                                                                                 |
        | teammate_ids                              | String                                                                                                                                                 |
        | admin_assignee_id                         | String                                                                                                                                                 |
        | team_assignee_id                          | String                                                                                                                                                 |
        | channel_initiated                         | String                                                                                                                                                 |
        | open                                      | Boolean                                                                                                                                                |
        | read                                      | Boolean                                                                                                                                                |
        | state                                     | String                                                                                                                                                 |
        | waiting_since                             | Date (UNIX timestamp)                                                                                                                                  |
        | snoozed_until                             | Date (UNIX timestamp)                                                                                                                                  |
        | tag_ids                                   | String                                                                                                                                                 |
        | priority                                  | String                                                                                                                                                 |
        | statistics.time_to_assignment             | Integer                                                                                                                                                |
        | statistics.time_to_admin_reply            | Integer                                                                                                                                                |
        | statistics.time_to_first_close            | Integer                                                                                                                                                |
        | statistics.time_to_last_close             | Integer                                                                                                                                                |
        | statistics.median_time_to_reply           | Integer                                                                                                                                                |
        | statistics.first_contact_reply_at         | Date (UNIX timestamp)                                                                                                                                  |
        | statistics.first_assignment_at            | Date (UNIX timestamp)                                                                                                                                  |
        | statistics.first_admin_reply_at           | Date (UNIX timestamp)                                                                                                                                  |
        | statistics.first_close_at                 | Date (UNIX timestamp)                                                                                                                                  |
        | statistics.last_assignment_at             | Date (UNIX timestamp)                                                                                                                                  |
        | statistics.last_assignment_admin_reply_at | Date (UNIX timestamp)                                                                                                                                  |
        | statistics.last_contact_reply_at          | Date (UNIX timestamp)                                                                                                                                  |
        | statistics.last_admin_reply_at            | Date (UNIX timestamp)                                                                                                                                  |
        | statistics.last_close_at                  | Date (UNIX timestamp)                                                                                                                                  |
        | statistics.last_closed_by_id              | String                                                                                                                                                 |
        | statistics.count_reopens                  | Integer                                                                                                                                                |
        | statistics.count_assignments              | Integer                                                                                                                                                |
        | statistics.count_conversation_parts       | Integer                                                                                                                                                |
        | conversation_rating.requested_at          | Date (UNIX timestamp)                                                                                                                                  |
        | conversation_rating.replied_at            | Date (UNIX timestamp)                                                                                                                                  |
        | conversation_rating.score                 | Integer                                                                                                                                                |
        | conversation_rating.remark                | String                                                                                                                                                 |
        | conversation_rating.contact_id            | String                                                                                                                                                 |
        | conversation_rating.admin_d               | String                                                                                                                                                 |
        | ai_agent_participated                     | Boolean                                                                                                                                                |
        | ai_agent.resolution_state                 | String                                                                                                                                                 |
        | ai_agent.last_answer_type                 | String                                                                                                                                                 |
        | ai_agent.rating                           | Integer                                                                                                                                                |
        | ai_agent.rating_remark                    | String                                                                                                                                                 |
        | ai_agent.source_type                      | String                                                                                                                                                 |
        | ai_agent.source_title                     | String                                                                                                                                                 |

        ### Accepted Operators

        The table below shows the operators you can use to define how you want to search for the value.  The operator should be put in as a string (`"="`). The operator has to be compatible with the field's type  (eg. you cannot search with `>` for a given string value as it's only compatible for integer's and dates).

        | Operator | Valid Types                    | Description                                                  |
        | :------- | :----------------------------- | :----------------------------------------------------------- |
        | =        | All                            | Equals                                                       |
        | !=       | All                            | Doesn't Equal                                                |
        | IN       | All                            | In  Shortcut for `OR` queries  Values most be in Array       |
        | NIN      | All                            | Not In  Shortcut for `OR !` queries  Values must be in Array |
        | >        | Integer  Date (UNIX Timestamp) | Greater (or equal) than                                      |
        | <       | Integer  Date (UNIX Timestamp) | Lower (or equal) than                                        |
        | ~        | String                         | Contains                                                     |
        | !~       | String                         | Doesn't Contain                                              |
        | ^        | String                         | Starts With                                                  |
        | $        | String                         | Ends With                                                    |

        Parameters
        ----------
        query : SearchRequestQuery

        pagination : typing.Optional[StartingAfterPaging]

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

        Returns
        -------
        AsyncPager[Conversation, ConversationList]
            successful
        """
        _response = await self._client_wrapper.httpx_client.request(
            "conversations/search",
            method="POST",
            json={
                "query": convert_and_respect_annotation_metadata(
                    object_=query, annotation=SearchRequestQuery, direction="write"
                ),
                "pagination": convert_and_respect_annotation_metadata(
                    object_=pagination, annotation=StartingAfterPaging, direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ConversationList,
                    construct_type(
                        type_=ConversationList,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _items = _parsed_response.conversations
                _has_next = False
                _get_next = None
                if _parsed_response.pages is not None and _parsed_response.pages.next is not None:
                    _parsed_next = _parsed_response.pages.next.starting_after
                    _has_next = _parsed_next is not None and _parsed_next != ""

                    async def _get_next():
                        return await self.search(
                            query=query,
                            pagination=pagination,
                            request_options=request_options,
                        )

                return AsyncPager(has_next=_has_next, items=_items, get_next=_get_next, response=_parsed_response)
            _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 reply(
        self,
        conversation_id: str,
        *,
        request: ReplyConversationRequest,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[Conversation]:
        """
        You can reply to a conversation with a message from an admin or on behalf of a contact, or with a note for admins.

        Parameters
        ----------
        conversation_id : str
            The Intercom provisioned identifier for the conversation or the string "last" to reply to the last part of the conversation

        request : ReplyConversationRequest

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

        Returns
        -------
        AsyncHttpResponse[Conversation]
            User last conversation reply
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"conversations/{jsonable_encoder(conversation_id)}/reply",
            method="POST",
            json=convert_and_respect_annotation_metadata(
                object_=request, annotation=ReplyConversationRequest, direction="write"
            ),
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Conversation,
                    construct_type(
                        type_=Conversation,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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 manage(
        self,
        conversation_id: str,
        *,
        request: ConversationsManageRequestBody,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[Conversation]:
        """
        For managing conversations you can:
        - Close a conversation
        - Snooze a conversation to reopen on a future date
        - Open a conversation which is `snoozed` or `closed`
        - Assign a conversation to an admin and/or team.

        Parameters
        ----------
        conversation_id : str
            The identifier for the conversation as given by Intercom.

        request : ConversationsManageRequestBody

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

        Returns
        -------
        AsyncHttpResponse[Conversation]
            Assign a conversation
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"conversations/{jsonable_encoder(conversation_id)}/parts",
            method="POST",
            json=convert_and_respect_annotation_metadata(
                object_=request, annotation=ConversationsManageRequestBody, direction="write"
            ),
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Conversation,
                    construct_type(
                        type_=Conversation,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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 attach_contact_as_admin(
        self,
        conversation_id: str,
        *,
        admin_id: typing.Optional[str] = OMIT,
        customer: typing.Optional[AttachContactToConversationRequestCustomer] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[Conversation]:
        """
        You can add participants who are contacts to a conversation, on behalf of either another contact or an admin.

        {% admonition type="warning" name="Contacts without an email" %}
        If you add a contact via the email parameter and there is no user/lead found on that workspace with he given email, then we will create a new contact with `role` set to `lead`.
        {% /admonition %}

        Parameters
        ----------
        conversation_id : str
            The identifier for the conversation as given by Intercom.

        admin_id : typing.Optional[str]
            The `id` of the admin who is adding the new participant.

        customer : typing.Optional[AttachContactToConversationRequestCustomer]

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

        Returns
        -------
        AsyncHttpResponse[Conversation]
            Attach a contact to a conversation
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"conversations/{jsonable_encoder(conversation_id)}/customers",
            method="POST",
            json={
                "admin_id": admin_id,
                "customer": convert_and_respect_annotation_metadata(
                    object_=customer, annotation=AttachContactToConversationRequestCustomer, direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Conversation,
                    construct_type(
                        type_=Conversation,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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 detach_contact_as_admin(
        self,
        conversation_id: str,
        contact_id: str,
        *,
        admin_id: str,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[Conversation]:
        """
        You can add participants who are contacts to a conversation, on behalf of either another contact or an admin.

        {% admonition type="warning" name="Contacts without an email" %}
        If you add a contact via the email parameter and there is no user/lead found on that workspace with he given email, then we will create a new contact with `role` set to `lead`.
        {% /admonition %}

        Parameters
        ----------
        conversation_id : str
            The identifier for the conversation as given by Intercom.

        contact_id : str
            The identifier for the contact as given by Intercom.

        admin_id : str
            The `id` of the admin who is performing the action.

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

        Returns
        -------
        AsyncHttpResponse[Conversation]
            Detach a contact from a group conversation
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"conversations/{jsonable_encoder(conversation_id)}/customers/{jsonable_encoder(contact_id)}",
            method="DELETE",
            json={
                "admin_id": admin_id,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Conversation,
                    construct_type(
                        type_=Conversation,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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 redact_conversation_part(
        self, *, request: RedactConversationRequest, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[Conversation]:
        """
        You can redact a conversation part or the source message of a conversation (as seen in the source object).

        {% admonition type="info" name="Redacting parts and messages" %}
        If you are redacting a conversation part, it must have a `body`. If you are redacting a source message, it must have been created by a contact. We will return a `conversation_part_not_redactable` error if these criteria are not met.
        {% /admonition %}

        Parameters
        ----------
        request : RedactConversationRequest

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

        Returns
        -------
        AsyncHttpResponse[Conversation]
            Redact a conversation part
        """
        _response = await self._client_wrapper.httpx_client.request(
            "conversations/redact",
            method="POST",
            json=convert_and_respect_annotation_metadata(
                object_=request, annotation=RedactConversationRequest, direction="write"
            ),
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Conversation,
                    construct_type(
                        type_=Conversation,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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 convert_to_ticket(
        self,
        conversation_id: int,
        *,
        ticket_type_id: str,
        attributes: typing.Optional[TicketRequestCustomAttributes] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[typing.Optional[Ticket]]:
        """
        You can convert a conversation to a ticket.

        Parameters
        ----------
        conversation_id : int
            The id of the conversation to target

        ticket_type_id : str
            The ID of the type of ticket you want to convert the conversation to

        attributes : typing.Optional[TicketRequestCustomAttributes]

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

        Returns
        -------
        AsyncHttpResponse[typing.Optional[Ticket]]
            successful
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"conversations/{jsonable_encoder(conversation_id)}/convert",
            method="POST",
            json={
                "ticket_type_id": ticket_type_id,
                "attributes": attributes,
            },
            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[Ticket],
                    construct_type(
                        type_=typing.Optional[Ticket],  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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 run_assignment_rules(
        self, conversation_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[Conversation]:
        """
        {% admonition type="danger" name="Deprecation of Run Assignment Rules" %}
        Run assignment rules is now deprecated in version 2.12 and future versions and will be permanently removed on December 31, 2026. After this date, any requests made to this endpoint will fail.
        {% /admonition %}
        You can let a conversation be automatically assigned following assignment rules.
        {% admonition type="warning" name="When using workflows" %}
        It is not possible to use this endpoint with Workflows.
        {% /admonition %}

        Parameters
        ----------
        conversation_id : str
            The identifier for the conversation as given by Intercom.

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

        Returns
        -------
        AsyncHttpResponse[Conversation]
            Assign a conversation using assignment rules
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"conversations/{jsonable_encoder(conversation_id)}/run_assignment_rules",
            method="POST",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Conversation,
                    construct_type(
                        type_=Conversation,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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)
