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

import typing
from json.decoder import JSONDecodeError

from ..commons.errors.bad_request_error import BadRequestError
from ..commons.errors.not_found_error import NotFoundError
from ..commons.errors.server_error import ServerError
from ..commons.types.entity_id_base import EntityIdBase
from ..commons.types.error_message import ErrorMessage
from ..core.api_error import ApiError
from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.http_response import AsyncHttpResponse, HttpResponse
from ..core.jsonable_encoder import jsonable_encoder
from ..core.pydantic_utilities import parse_obj_as
from ..core.request_options import RequestOptions
from ..core.serialization import convert_and_respect_annotation_metadata
from .types.customer_field import CustomerField
from .types.customer_filter import CustomerFilter
from .types.customer_response import CustomerResponse
from .types.customer_status import CustomerStatus
from .types.customers_search_response import CustomersSearchResponse

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


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

    def search(
        self,
        *,
        sort: typing.Optional[CustomerField] = OMIT,
        filter: typing.Optional[CustomerFilter] = OMIT,
        page: typing.Optional[int] = OMIT,
        size: typing.Optional[int] = OMIT,
        sort_desc: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[CustomersSearchResponse]:
        """
        Parameters
        ----------
        sort : typing.Optional[CustomerField]
            The field to sort by, defaults to created timestamp

        filter : typing.Optional[CustomerFilter]
            The filter to apply to the customers.

        page : typing.Optional[int]
            Page number to return, defaults to 0

        size : typing.Optional[int]
            The size of the page to return, defaults to 20

        sort_desc : typing.Optional[bool]
            Whether to sort descending, defaults to true

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

        Returns
        -------
        HttpResponse[CustomersSearchResponse]
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/customers",
            method="POST",
            json={
                "sort": sort,
                "filter": convert_and_respect_annotation_metadata(
                    object_=filter, annotation=CustomerFilter, direction="write"
                ),
                "page": page,
                "size": size,
                "sortDesc": sort_desc,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    CustomersSearchResponse,
                    parse_obj_as(
                        type_=CustomersSearchResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise ServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # 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_or_update(
        self, *, customer_id: EntityIdBase, name: str, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[CustomerResponse]:
        """
        Update a customer of an agent or create it if it doesn't exist. In case of an update, fields not provided (e.g., description, status) will be preserved.

        Parameters
        ----------
        customer_id : EntityIdBase
            ID that uniquely identifies this customer

        name : str

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

        Returns
        -------
        HttpResponse[CustomerResponse]
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/customers",
            method="PUT",
            json={
                "customerId": convert_and_respect_annotation_metadata(
                    object_=customer_id, annotation=EntityIdBase, direction="write"
                ),
                "name": name,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    CustomerResponse,
                    parse_obj_as(
                        type_=CustomerResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise ServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def get(
        self,
        customer_reference_id: str,
        *,
        app_id: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[CustomerResponse]:
        """
        Get a customer by its supplied ID

        Parameters
        ----------
        customer_reference_id : str
            The reference ID of the customer to get. All other entity ID fields are inferred from the request.

        app_id : typing.Optional[str]
            The App ID of the customer to get. If not provided, the ID of the calling app will be used.

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

        Returns
        -------
        HttpResponse[CustomerResponse]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/customers/{jsonable_encoder(customer_reference_id)}",
            method="GET",
            params={
                "appId": app_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    CustomerResponse,
                    parse_obj_as(
                        type_=CustomerResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise ServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # 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 patch(
        self,
        customer_reference_id: str,
        *,
        app_id: typing.Optional[str] = OMIT,
        name: typing.Optional[str] = OMIT,
        description: typing.Optional[str] = OMIT,
        status: typing.Optional[CustomerStatus] = OMIT,
        metadata: typing.Optional[typing.Dict[str, str]] = OMIT,
        assignees: typing.Optional[typing.Set[str]] = OMIT,
        members: typing.Optional[typing.Set[str]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[CustomerResponse]:
        """
        Update mutable customer fields

        The `appId` field can be provided to update a customer owned by a different app.
        All other fields will overwrite the existing value on the customer only if provided.

        Parameters
        ----------
        customer_reference_id : str
            The reference ID of the customer to update. All other entity ID fields are inferred from the request.

        app_id : typing.Optional[str]
            The App ID of the customer to update. If not provided, the ID of the calling app will be used.

        name : typing.Optional[str]
            The name of the customer.

        description : typing.Optional[str]
            The description of the customer.

        status : typing.Optional[CustomerStatus]
            Whether or not the customer is in active use.

            Only active customers will be available for agent interactions.

        metadata : typing.Optional[typing.Dict[str, str]]
            Metadata associated with the customer. If not provided, the existing metadata will be preserved.

        assignees : typing.Optional[typing.Set[str]]
            Set of agent user IDs to assign to this customer. If provided, replaces all existing assignees.

        members : typing.Optional[typing.Set[str]]
            Set of agent user IDs who are members of this customer. If provided, replaces all existing members.

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

        Returns
        -------
        HttpResponse[CustomerResponse]
            The updated customer
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/customers/{jsonable_encoder(customer_reference_id)}",
            method="PATCH",
            json={
                "appId": app_id,
                "name": name,
                "description": description,
                "status": status,
                "metadata": metadata,
                "assignees": assignees,
                "members": members,
            },
            headers={
                "content-type": "application/merge-patch+json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    CustomerResponse,
                    parse_obj_as(
                        type_=CustomerResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise ServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # 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 AsyncRawCustomersClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def search(
        self,
        *,
        sort: typing.Optional[CustomerField] = OMIT,
        filter: typing.Optional[CustomerFilter] = OMIT,
        page: typing.Optional[int] = OMIT,
        size: typing.Optional[int] = OMIT,
        sort_desc: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[CustomersSearchResponse]:
        """
        Parameters
        ----------
        sort : typing.Optional[CustomerField]
            The field to sort by, defaults to created timestamp

        filter : typing.Optional[CustomerFilter]
            The filter to apply to the customers.

        page : typing.Optional[int]
            Page number to return, defaults to 0

        size : typing.Optional[int]
            The size of the page to return, defaults to 20

        sort_desc : typing.Optional[bool]
            Whether to sort descending, defaults to true

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

        Returns
        -------
        AsyncHttpResponse[CustomersSearchResponse]
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/customers",
            method="POST",
            json={
                "sort": sort,
                "filter": convert_and_respect_annotation_metadata(
                    object_=filter, annotation=CustomerFilter, direction="write"
                ),
                "page": page,
                "size": size,
                "sortDesc": sort_desc,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    CustomersSearchResponse,
                    parse_obj_as(
                        type_=CustomersSearchResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise ServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # 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_or_update(
        self, *, customer_id: EntityIdBase, name: str, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[CustomerResponse]:
        """
        Update a customer of an agent or create it if it doesn't exist. In case of an update, fields not provided (e.g., description, status) will be preserved.

        Parameters
        ----------
        customer_id : EntityIdBase
            ID that uniquely identifies this customer

        name : str

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

        Returns
        -------
        AsyncHttpResponse[CustomerResponse]
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/customers",
            method="PUT",
            json={
                "customerId": convert_and_respect_annotation_metadata(
                    object_=customer_id, annotation=EntityIdBase, direction="write"
                ),
                "name": name,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    CustomerResponse,
                    parse_obj_as(
                        type_=CustomerResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise ServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def get(
        self,
        customer_reference_id: str,
        *,
        app_id: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[CustomerResponse]:
        """
        Get a customer by its supplied ID

        Parameters
        ----------
        customer_reference_id : str
            The reference ID of the customer to get. All other entity ID fields are inferred from the request.

        app_id : typing.Optional[str]
            The App ID of the customer to get. If not provided, the ID of the calling app will be used.

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

        Returns
        -------
        AsyncHttpResponse[CustomerResponse]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/customers/{jsonable_encoder(customer_reference_id)}",
            method="GET",
            params={
                "appId": app_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    CustomerResponse,
                    parse_obj_as(
                        type_=CustomerResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise ServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # 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 patch(
        self,
        customer_reference_id: str,
        *,
        app_id: typing.Optional[str] = OMIT,
        name: typing.Optional[str] = OMIT,
        description: typing.Optional[str] = OMIT,
        status: typing.Optional[CustomerStatus] = OMIT,
        metadata: typing.Optional[typing.Dict[str, str]] = OMIT,
        assignees: typing.Optional[typing.Set[str]] = OMIT,
        members: typing.Optional[typing.Set[str]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[CustomerResponse]:
        """
        Update mutable customer fields

        The `appId` field can be provided to update a customer owned by a different app.
        All other fields will overwrite the existing value on the customer only if provided.

        Parameters
        ----------
        customer_reference_id : str
            The reference ID of the customer to update. All other entity ID fields are inferred from the request.

        app_id : typing.Optional[str]
            The App ID of the customer to update. If not provided, the ID of the calling app will be used.

        name : typing.Optional[str]
            The name of the customer.

        description : typing.Optional[str]
            The description of the customer.

        status : typing.Optional[CustomerStatus]
            Whether or not the customer is in active use.

            Only active customers will be available for agent interactions.

        metadata : typing.Optional[typing.Dict[str, str]]
            Metadata associated with the customer. If not provided, the existing metadata will be preserved.

        assignees : typing.Optional[typing.Set[str]]
            Set of agent user IDs to assign to this customer. If provided, replaces all existing assignees.

        members : typing.Optional[typing.Set[str]]
            Set of agent user IDs who are members of this customer. If provided, replaces all existing members.

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

        Returns
        -------
        AsyncHttpResponse[CustomerResponse]
            The updated customer
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/customers/{jsonable_encoder(customer_reference_id)}",
            method="PATCH",
            json={
                "appId": app_id,
                "name": name,
                "description": description,
                "status": status,
                "metadata": metadata,
                "assignees": assignees,
                "members": members,
            },
            headers={
                "content-type": "application/merge-patch+json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    CustomerResponse,
                    parse_obj_as(
                        type_=CustomerResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise ServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # 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)
