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

import typing
import urllib.parse
from json.decoder import JSONDecodeError

from ..core.api_error import ApiError as core_api_error_ApiError
from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.jsonable_encoder import jsonable_encoder
from ..core.pydantic_utilities import pydantic_v1
from ..core.query_encoder import encode_query
from ..core.remove_none_from_dict import remove_none_from_dict
from ..core.request_options import RequestOptions
from ..errors.bad_request_error import BadRequestError
from ..errors.forbidden_error import ForbiddenError
from ..errors.internal_server_error import InternalServerError
from ..errors.unauthorized_error import UnauthorizedError
from ..types.api_error import ApiError as types_api_error_ApiError
from .types.list_crm_products_response import ListCrmProductsResponse
from .types.upsert_crm_deal_response import UpsertCrmDealResponse
from .types.upsert_crm_product_response import UpsertCrmProductResponse
from .types.upsert_deal_line_item_association_response import UpsertDealLineItemAssociationResponse
from .types.upsert_line_item_response import UpsertLineItemResponse

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


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

    def upsert_deal_line_item_association(
        self,
        *,
        deal_external_id: str,
        line_item_external_id: str,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> UpsertDealLineItemAssociationResponse:
        """
        Parameters
        ----------
        deal_external_id : str

        line_item_external_id : str

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

        Returns
        -------
        UpsertDealLineItemAssociationResponse
            Created

        Examples
        --------
        from schematic.client import Schematic

        client = Schematic(
            api_key="YOUR_API_KEY",
        )
        client.crm.upsert_deal_line_item_association(
            deal_external_id="deal_external_id",
            line_item_external_id="line_item_external_id",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            method="POST",
            url=urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "crm/associations/deal-line-item"),
            params=encode_query(
                jsonable_encoder(
                    request_options.get("additional_query_parameters") if request_options is not None else None
                )
            ),
            json=jsonable_encoder(
                {"deal_external_id": deal_external_id, "line_item_external_id": line_item_external_id}
            )
            if request_options is None or request_options.get("additional_body_parameters") is None
            else {
                **jsonable_encoder(
                    {"deal_external_id": deal_external_id, "line_item_external_id": line_item_external_id}
                ),
                **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))),
            },
            headers=jsonable_encoder(
                remove_none_from_dict(
                    {
                        **self._client_wrapper.get_headers(),
                        **(request_options.get("additional_headers", {}) if request_options is not None else {}),
                    }
                )
            ),
            timeout=request_options.get("timeout_in_seconds")
            if request_options is not None and request_options.get("timeout_in_seconds") is not None
            else self._client_wrapper.get_timeout(),
            retries=0,
            max_retries=request_options.get("max_retries") if request_options is not None else 0,  # type: ignore
        )
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(UpsertDealLineItemAssociationResponse, _response.json())  # type: ignore
        if _response.status_code == 400:
            raise BadRequestError(pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json()))  # type: ignore
        if _response.status_code == 401:
            raise UnauthorizedError(
                pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json())  # type: ignore
            )
        if _response.status_code == 403:
            raise ForbiddenError(pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json()))  # type: ignore
        if _response.status_code == 500:
            raise InternalServerError(
                pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json())  # type: ignore
            )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise core_api_error_ApiError(status_code=_response.status_code, body=_response.text)
        raise core_api_error_ApiError(status_code=_response.status_code, body=_response_json)

    def upsert_line_item(
        self,
        *,
        amount: str,
        interval: str,
        line_item_external_id: str,
        product_external_id: str,
        quantity: int,
        term_month: typing.Optional[int] = OMIT,
        discount_percentage: typing.Optional[str] = OMIT,
        total_discount: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> UpsertLineItemResponse:
        """
        Parameters
        ----------
        amount : str

        interval : str

        line_item_external_id : str

        product_external_id : str

        quantity : int

        term_month : typing.Optional[int]

        discount_percentage : typing.Optional[str]

        total_discount : typing.Optional[str]

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

        Returns
        -------
        UpsertLineItemResponse
            Created

        Examples
        --------
        from schematic.client import Schematic

        client = Schematic(
            api_key="YOUR_API_KEY",
        )
        client.crm.upsert_line_item(
            amount="amount",
            interval="interval",
            line_item_external_id="line_item_external_id",
            product_external_id="product_external_id",
            quantity=1,
        )
        """
        _request: typing.Dict[str, typing.Any] = {
            "amount": amount,
            "interval": interval,
            "line_item_external_id": line_item_external_id,
            "product_external_id": product_external_id,
            "quantity": quantity,
        }
        if term_month is not OMIT:
            _request["TermMonth"] = term_month
        if discount_percentage is not OMIT:
            _request["discount_percentage"] = discount_percentage
        if total_discount is not OMIT:
            _request["total_discount"] = total_discount
        _response = self._client_wrapper.httpx_client.request(
            method="POST",
            url=urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "crm/deal-line-item/upsert"),
            params=encode_query(
                jsonable_encoder(
                    request_options.get("additional_query_parameters") if request_options is not None else None
                )
            ),
            json=jsonable_encoder(_request)
            if request_options is None or request_options.get("additional_body_parameters") is None
            else {
                **jsonable_encoder(_request),
                **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))),
            },
            headers=jsonable_encoder(
                remove_none_from_dict(
                    {
                        **self._client_wrapper.get_headers(),
                        **(request_options.get("additional_headers", {}) if request_options is not None else {}),
                    }
                )
            ),
            timeout=request_options.get("timeout_in_seconds")
            if request_options is not None and request_options.get("timeout_in_seconds") is not None
            else self._client_wrapper.get_timeout(),
            retries=0,
            max_retries=request_options.get("max_retries") if request_options is not None else 0,  # type: ignore
        )
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(UpsertLineItemResponse, _response.json())  # type: ignore
        if _response.status_code == 400:
            raise BadRequestError(pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json()))  # type: ignore
        if _response.status_code == 401:
            raise UnauthorizedError(
                pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json())  # type: ignore
            )
        if _response.status_code == 403:
            raise ForbiddenError(pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json()))  # type: ignore
        if _response.status_code == 500:
            raise InternalServerError(
                pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json())  # type: ignore
            )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise core_api_error_ApiError(status_code=_response.status_code, body=_response.text)
        raise core_api_error_ApiError(status_code=_response.status_code, body=_response_json)

    def upsert_crm_deal(
        self,
        *,
        crm_company_key: str,
        crm_type: str,
        deal_external_id: str,
        arr: typing.Optional[str] = OMIT,
        crm_company_id: typing.Optional[str] = OMIT,
        crm_product_id: typing.Optional[str] = OMIT,
        deal_name: typing.Optional[str] = OMIT,
        deal_stage: typing.Optional[str] = OMIT,
        mrr: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> UpsertCrmDealResponse:
        """
        Parameters
        ----------
        crm_company_key : str

        crm_type : str

        deal_external_id : str

        arr : typing.Optional[str]

        crm_company_id : typing.Optional[str]

        crm_product_id : typing.Optional[str]

        deal_name : typing.Optional[str]

        deal_stage : typing.Optional[str]

        mrr : typing.Optional[str]

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

        Returns
        -------
        UpsertCrmDealResponse
            Created

        Examples
        --------
        from schematic.client import Schematic

        client = Schematic(
            api_key="YOUR_API_KEY",
        )
        client.crm.upsert_crm_deal(
            crm_company_key="crm_company_key",
            crm_type="crm_type",
            deal_external_id="deal_external_id",
        )
        """
        _request: typing.Dict[str, typing.Any] = {
            "crm_company_key": crm_company_key,
            "crm_type": crm_type,
            "deal_external_id": deal_external_id,
        }
        if arr is not OMIT:
            _request["arr"] = arr
        if crm_company_id is not OMIT:
            _request["crm_company_id"] = crm_company_id
        if crm_product_id is not OMIT:
            _request["crm_product_id"] = crm_product_id
        if deal_name is not OMIT:
            _request["deal_name"] = deal_name
        if deal_stage is not OMIT:
            _request["deal_stage"] = deal_stage
        if mrr is not OMIT:
            _request["mrr"] = mrr
        _response = self._client_wrapper.httpx_client.request(
            method="POST",
            url=urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "crm/deals/upsert"),
            params=encode_query(
                jsonable_encoder(
                    request_options.get("additional_query_parameters") if request_options is not None else None
                )
            ),
            json=jsonable_encoder(_request)
            if request_options is None or request_options.get("additional_body_parameters") is None
            else {
                **jsonable_encoder(_request),
                **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))),
            },
            headers=jsonable_encoder(
                remove_none_from_dict(
                    {
                        **self._client_wrapper.get_headers(),
                        **(request_options.get("additional_headers", {}) if request_options is not None else {}),
                    }
                )
            ),
            timeout=request_options.get("timeout_in_seconds")
            if request_options is not None and request_options.get("timeout_in_seconds") is not None
            else self._client_wrapper.get_timeout(),
            retries=0,
            max_retries=request_options.get("max_retries") if request_options is not None else 0,  # type: ignore
        )
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(UpsertCrmDealResponse, _response.json())  # type: ignore
        if _response.status_code == 400:
            raise BadRequestError(pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json()))  # type: ignore
        if _response.status_code == 401:
            raise UnauthorizedError(
                pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json())  # type: ignore
            )
        if _response.status_code == 403:
            raise ForbiddenError(pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json()))  # type: ignore
        if _response.status_code == 500:
            raise InternalServerError(
                pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json())  # type: ignore
            )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise core_api_error_ApiError(status_code=_response.status_code, body=_response.text)
        raise core_api_error_ApiError(status_code=_response.status_code, body=_response_json)

    def list_crm_products(
        self,
        *,
        ids: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        name: typing.Optional[str] = None,
        limit: typing.Optional[int] = None,
        offset: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> ListCrmProductsResponse:
        """
        Parameters
        ----------
        ids : typing.Optional[typing.Union[str, typing.Sequence[str]]]

        name : typing.Optional[str]

        limit : typing.Optional[int]
            Page limit (default 100)

        offset : typing.Optional[int]
            Page offset (default 0)

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

        Returns
        -------
        ListCrmProductsResponse
            OK

        Examples
        --------
        from schematic.client import Schematic

        client = Schematic(
            api_key="YOUR_API_KEY",
        )
        client.crm.list_crm_products()
        """
        _response = self._client_wrapper.httpx_client.request(
            method="GET",
            url=urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "crm/products"),
            params=encode_query(
                jsonable_encoder(
                    remove_none_from_dict(
                        {
                            "ids": ids,
                            "name": name,
                            "limit": limit,
                            "offset": offset,
                            **(
                                request_options.get("additional_query_parameters", {})
                                if request_options is not None
                                else {}
                            ),
                        }
                    )
                )
            ),
            headers=jsonable_encoder(
                remove_none_from_dict(
                    {
                        **self._client_wrapper.get_headers(),
                        **(request_options.get("additional_headers", {}) if request_options is not None else {}),
                    }
                )
            ),
            timeout=request_options.get("timeout_in_seconds")
            if request_options is not None and request_options.get("timeout_in_seconds") is not None
            else self._client_wrapper.get_timeout(),
            retries=0,
            max_retries=request_options.get("max_retries") if request_options is not None else 0,  # type: ignore
        )
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(ListCrmProductsResponse, _response.json())  # type: ignore
        if _response.status_code == 400:
            raise BadRequestError(pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json()))  # type: ignore
        if _response.status_code == 401:
            raise UnauthorizedError(
                pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json())  # type: ignore
            )
        if _response.status_code == 403:
            raise ForbiddenError(pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json()))  # type: ignore
        if _response.status_code == 500:
            raise InternalServerError(
                pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json())  # type: ignore
            )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise core_api_error_ApiError(status_code=_response.status_code, body=_response.text)
        raise core_api_error_ApiError(status_code=_response.status_code, body=_response_json)

    def upsert_crm_product(
        self,
        *,
        currency: str,
        description: str,
        external_id: str,
        interval: str,
        name: str,
        price: str,
        quantity: int,
        sku: str,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> UpsertCrmProductResponse:
        """
        Parameters
        ----------
        currency : str

        description : str

        external_id : str

        interval : str

        name : str

        price : str

        quantity : int

        sku : str

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

        Returns
        -------
        UpsertCrmProductResponse
            Created

        Examples
        --------
        from schematic.client import Schematic

        client = Schematic(
            api_key="YOUR_API_KEY",
        )
        client.crm.upsert_crm_product(
            currency="currency",
            description="description",
            external_id="external_id",
            interval="interval",
            name="name",
            price="price",
            quantity=1,
            sku="sku",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            method="POST",
            url=urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "crm/products/upsert"),
            params=encode_query(
                jsonable_encoder(
                    request_options.get("additional_query_parameters") if request_options is not None else None
                )
            ),
            json=jsonable_encoder(
                {
                    "currency": currency,
                    "description": description,
                    "external_id": external_id,
                    "interval": interval,
                    "name": name,
                    "price": price,
                    "quantity": quantity,
                    "sku": sku,
                }
            )
            if request_options is None or request_options.get("additional_body_parameters") is None
            else {
                **jsonable_encoder(
                    {
                        "currency": currency,
                        "description": description,
                        "external_id": external_id,
                        "interval": interval,
                        "name": name,
                        "price": price,
                        "quantity": quantity,
                        "sku": sku,
                    }
                ),
                **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))),
            },
            headers=jsonable_encoder(
                remove_none_from_dict(
                    {
                        **self._client_wrapper.get_headers(),
                        **(request_options.get("additional_headers", {}) if request_options is not None else {}),
                    }
                )
            ),
            timeout=request_options.get("timeout_in_seconds")
            if request_options is not None and request_options.get("timeout_in_seconds") is not None
            else self._client_wrapper.get_timeout(),
            retries=0,
            max_retries=request_options.get("max_retries") if request_options is not None else 0,  # type: ignore
        )
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(UpsertCrmProductResponse, _response.json())  # type: ignore
        if _response.status_code == 400:
            raise BadRequestError(pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json()))  # type: ignore
        if _response.status_code == 401:
            raise UnauthorizedError(
                pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json())  # type: ignore
            )
        if _response.status_code == 403:
            raise ForbiddenError(pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json()))  # type: ignore
        if _response.status_code == 500:
            raise InternalServerError(
                pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json())  # type: ignore
            )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise core_api_error_ApiError(status_code=_response.status_code, body=_response.text)
        raise core_api_error_ApiError(status_code=_response.status_code, body=_response_json)


class AsyncCrmClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def upsert_deal_line_item_association(
        self,
        *,
        deal_external_id: str,
        line_item_external_id: str,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> UpsertDealLineItemAssociationResponse:
        """
        Parameters
        ----------
        deal_external_id : str

        line_item_external_id : str

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

        Returns
        -------
        UpsertDealLineItemAssociationResponse
            Created

        Examples
        --------
        from schematic.client import AsyncSchematic

        client = AsyncSchematic(
            api_key="YOUR_API_KEY",
        )
        await client.crm.upsert_deal_line_item_association(
            deal_external_id="deal_external_id",
            line_item_external_id="line_item_external_id",
        )
        """
        _response = await self._client_wrapper.httpx_client.request(
            method="POST",
            url=urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "crm/associations/deal-line-item"),
            params=encode_query(
                jsonable_encoder(
                    request_options.get("additional_query_parameters") if request_options is not None else None
                )
            ),
            json=jsonable_encoder(
                {"deal_external_id": deal_external_id, "line_item_external_id": line_item_external_id}
            )
            if request_options is None or request_options.get("additional_body_parameters") is None
            else {
                **jsonable_encoder(
                    {"deal_external_id": deal_external_id, "line_item_external_id": line_item_external_id}
                ),
                **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))),
            },
            headers=jsonable_encoder(
                remove_none_from_dict(
                    {
                        **self._client_wrapper.get_headers(),
                        **(request_options.get("additional_headers", {}) if request_options is not None else {}),
                    }
                )
            ),
            timeout=request_options.get("timeout_in_seconds")
            if request_options is not None and request_options.get("timeout_in_seconds") is not None
            else self._client_wrapper.get_timeout(),
            retries=0,
            max_retries=request_options.get("max_retries") if request_options is not None else 0,  # type: ignore
        )
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(UpsertDealLineItemAssociationResponse, _response.json())  # type: ignore
        if _response.status_code == 400:
            raise BadRequestError(pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json()))  # type: ignore
        if _response.status_code == 401:
            raise UnauthorizedError(
                pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json())  # type: ignore
            )
        if _response.status_code == 403:
            raise ForbiddenError(pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json()))  # type: ignore
        if _response.status_code == 500:
            raise InternalServerError(
                pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json())  # type: ignore
            )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise core_api_error_ApiError(status_code=_response.status_code, body=_response.text)
        raise core_api_error_ApiError(status_code=_response.status_code, body=_response_json)

    async def upsert_line_item(
        self,
        *,
        amount: str,
        interval: str,
        line_item_external_id: str,
        product_external_id: str,
        quantity: int,
        term_month: typing.Optional[int] = OMIT,
        discount_percentage: typing.Optional[str] = OMIT,
        total_discount: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> UpsertLineItemResponse:
        """
        Parameters
        ----------
        amount : str

        interval : str

        line_item_external_id : str

        product_external_id : str

        quantity : int

        term_month : typing.Optional[int]

        discount_percentage : typing.Optional[str]

        total_discount : typing.Optional[str]

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

        Returns
        -------
        UpsertLineItemResponse
            Created

        Examples
        --------
        from schematic.client import AsyncSchematic

        client = AsyncSchematic(
            api_key="YOUR_API_KEY",
        )
        await client.crm.upsert_line_item(
            amount="amount",
            interval="interval",
            line_item_external_id="line_item_external_id",
            product_external_id="product_external_id",
            quantity=1,
        )
        """
        _request: typing.Dict[str, typing.Any] = {
            "amount": amount,
            "interval": interval,
            "line_item_external_id": line_item_external_id,
            "product_external_id": product_external_id,
            "quantity": quantity,
        }
        if term_month is not OMIT:
            _request["TermMonth"] = term_month
        if discount_percentage is not OMIT:
            _request["discount_percentage"] = discount_percentage
        if total_discount is not OMIT:
            _request["total_discount"] = total_discount
        _response = await self._client_wrapper.httpx_client.request(
            method="POST",
            url=urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "crm/deal-line-item/upsert"),
            params=encode_query(
                jsonable_encoder(
                    request_options.get("additional_query_parameters") if request_options is not None else None
                )
            ),
            json=jsonable_encoder(_request)
            if request_options is None or request_options.get("additional_body_parameters") is None
            else {
                **jsonable_encoder(_request),
                **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))),
            },
            headers=jsonable_encoder(
                remove_none_from_dict(
                    {
                        **self._client_wrapper.get_headers(),
                        **(request_options.get("additional_headers", {}) if request_options is not None else {}),
                    }
                )
            ),
            timeout=request_options.get("timeout_in_seconds")
            if request_options is not None and request_options.get("timeout_in_seconds") is not None
            else self._client_wrapper.get_timeout(),
            retries=0,
            max_retries=request_options.get("max_retries") if request_options is not None else 0,  # type: ignore
        )
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(UpsertLineItemResponse, _response.json())  # type: ignore
        if _response.status_code == 400:
            raise BadRequestError(pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json()))  # type: ignore
        if _response.status_code == 401:
            raise UnauthorizedError(
                pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json())  # type: ignore
            )
        if _response.status_code == 403:
            raise ForbiddenError(pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json()))  # type: ignore
        if _response.status_code == 500:
            raise InternalServerError(
                pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json())  # type: ignore
            )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise core_api_error_ApiError(status_code=_response.status_code, body=_response.text)
        raise core_api_error_ApiError(status_code=_response.status_code, body=_response_json)

    async def upsert_crm_deal(
        self,
        *,
        crm_company_key: str,
        crm_type: str,
        deal_external_id: str,
        arr: typing.Optional[str] = OMIT,
        crm_company_id: typing.Optional[str] = OMIT,
        crm_product_id: typing.Optional[str] = OMIT,
        deal_name: typing.Optional[str] = OMIT,
        deal_stage: typing.Optional[str] = OMIT,
        mrr: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> UpsertCrmDealResponse:
        """
        Parameters
        ----------
        crm_company_key : str

        crm_type : str

        deal_external_id : str

        arr : typing.Optional[str]

        crm_company_id : typing.Optional[str]

        crm_product_id : typing.Optional[str]

        deal_name : typing.Optional[str]

        deal_stage : typing.Optional[str]

        mrr : typing.Optional[str]

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

        Returns
        -------
        UpsertCrmDealResponse
            Created

        Examples
        --------
        from schematic.client import AsyncSchematic

        client = AsyncSchematic(
            api_key="YOUR_API_KEY",
        )
        await client.crm.upsert_crm_deal(
            crm_company_key="crm_company_key",
            crm_type="crm_type",
            deal_external_id="deal_external_id",
        )
        """
        _request: typing.Dict[str, typing.Any] = {
            "crm_company_key": crm_company_key,
            "crm_type": crm_type,
            "deal_external_id": deal_external_id,
        }
        if arr is not OMIT:
            _request["arr"] = arr
        if crm_company_id is not OMIT:
            _request["crm_company_id"] = crm_company_id
        if crm_product_id is not OMIT:
            _request["crm_product_id"] = crm_product_id
        if deal_name is not OMIT:
            _request["deal_name"] = deal_name
        if deal_stage is not OMIT:
            _request["deal_stage"] = deal_stage
        if mrr is not OMIT:
            _request["mrr"] = mrr
        _response = await self._client_wrapper.httpx_client.request(
            method="POST",
            url=urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "crm/deals/upsert"),
            params=encode_query(
                jsonable_encoder(
                    request_options.get("additional_query_parameters") if request_options is not None else None
                )
            ),
            json=jsonable_encoder(_request)
            if request_options is None or request_options.get("additional_body_parameters") is None
            else {
                **jsonable_encoder(_request),
                **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))),
            },
            headers=jsonable_encoder(
                remove_none_from_dict(
                    {
                        **self._client_wrapper.get_headers(),
                        **(request_options.get("additional_headers", {}) if request_options is not None else {}),
                    }
                )
            ),
            timeout=request_options.get("timeout_in_seconds")
            if request_options is not None and request_options.get("timeout_in_seconds") is not None
            else self._client_wrapper.get_timeout(),
            retries=0,
            max_retries=request_options.get("max_retries") if request_options is not None else 0,  # type: ignore
        )
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(UpsertCrmDealResponse, _response.json())  # type: ignore
        if _response.status_code == 400:
            raise BadRequestError(pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json()))  # type: ignore
        if _response.status_code == 401:
            raise UnauthorizedError(
                pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json())  # type: ignore
            )
        if _response.status_code == 403:
            raise ForbiddenError(pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json()))  # type: ignore
        if _response.status_code == 500:
            raise InternalServerError(
                pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json())  # type: ignore
            )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise core_api_error_ApiError(status_code=_response.status_code, body=_response.text)
        raise core_api_error_ApiError(status_code=_response.status_code, body=_response_json)

    async def list_crm_products(
        self,
        *,
        ids: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        name: typing.Optional[str] = None,
        limit: typing.Optional[int] = None,
        offset: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> ListCrmProductsResponse:
        """
        Parameters
        ----------
        ids : typing.Optional[typing.Union[str, typing.Sequence[str]]]

        name : typing.Optional[str]

        limit : typing.Optional[int]
            Page limit (default 100)

        offset : typing.Optional[int]
            Page offset (default 0)

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

        Returns
        -------
        ListCrmProductsResponse
            OK

        Examples
        --------
        from schematic.client import AsyncSchematic

        client = AsyncSchematic(
            api_key="YOUR_API_KEY",
        )
        await client.crm.list_crm_products()
        """
        _response = await self._client_wrapper.httpx_client.request(
            method="GET",
            url=urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "crm/products"),
            params=encode_query(
                jsonable_encoder(
                    remove_none_from_dict(
                        {
                            "ids": ids,
                            "name": name,
                            "limit": limit,
                            "offset": offset,
                            **(
                                request_options.get("additional_query_parameters", {})
                                if request_options is not None
                                else {}
                            ),
                        }
                    )
                )
            ),
            headers=jsonable_encoder(
                remove_none_from_dict(
                    {
                        **self._client_wrapper.get_headers(),
                        **(request_options.get("additional_headers", {}) if request_options is not None else {}),
                    }
                )
            ),
            timeout=request_options.get("timeout_in_seconds")
            if request_options is not None and request_options.get("timeout_in_seconds") is not None
            else self._client_wrapper.get_timeout(),
            retries=0,
            max_retries=request_options.get("max_retries") if request_options is not None else 0,  # type: ignore
        )
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(ListCrmProductsResponse, _response.json())  # type: ignore
        if _response.status_code == 400:
            raise BadRequestError(pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json()))  # type: ignore
        if _response.status_code == 401:
            raise UnauthorizedError(
                pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json())  # type: ignore
            )
        if _response.status_code == 403:
            raise ForbiddenError(pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json()))  # type: ignore
        if _response.status_code == 500:
            raise InternalServerError(
                pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json())  # type: ignore
            )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise core_api_error_ApiError(status_code=_response.status_code, body=_response.text)
        raise core_api_error_ApiError(status_code=_response.status_code, body=_response_json)

    async def upsert_crm_product(
        self,
        *,
        currency: str,
        description: str,
        external_id: str,
        interval: str,
        name: str,
        price: str,
        quantity: int,
        sku: str,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> UpsertCrmProductResponse:
        """
        Parameters
        ----------
        currency : str

        description : str

        external_id : str

        interval : str

        name : str

        price : str

        quantity : int

        sku : str

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

        Returns
        -------
        UpsertCrmProductResponse
            Created

        Examples
        --------
        from schematic.client import AsyncSchematic

        client = AsyncSchematic(
            api_key="YOUR_API_KEY",
        )
        await client.crm.upsert_crm_product(
            currency="currency",
            description="description",
            external_id="external_id",
            interval="interval",
            name="name",
            price="price",
            quantity=1,
            sku="sku",
        )
        """
        _response = await self._client_wrapper.httpx_client.request(
            method="POST",
            url=urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "crm/products/upsert"),
            params=encode_query(
                jsonable_encoder(
                    request_options.get("additional_query_parameters") if request_options is not None else None
                )
            ),
            json=jsonable_encoder(
                {
                    "currency": currency,
                    "description": description,
                    "external_id": external_id,
                    "interval": interval,
                    "name": name,
                    "price": price,
                    "quantity": quantity,
                    "sku": sku,
                }
            )
            if request_options is None or request_options.get("additional_body_parameters") is None
            else {
                **jsonable_encoder(
                    {
                        "currency": currency,
                        "description": description,
                        "external_id": external_id,
                        "interval": interval,
                        "name": name,
                        "price": price,
                        "quantity": quantity,
                        "sku": sku,
                    }
                ),
                **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))),
            },
            headers=jsonable_encoder(
                remove_none_from_dict(
                    {
                        **self._client_wrapper.get_headers(),
                        **(request_options.get("additional_headers", {}) if request_options is not None else {}),
                    }
                )
            ),
            timeout=request_options.get("timeout_in_seconds")
            if request_options is not None and request_options.get("timeout_in_seconds") is not None
            else self._client_wrapper.get_timeout(),
            retries=0,
            max_retries=request_options.get("max_retries") if request_options is not None else 0,  # type: ignore
        )
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(UpsertCrmProductResponse, _response.json())  # type: ignore
        if _response.status_code == 400:
            raise BadRequestError(pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json()))  # type: ignore
        if _response.status_code == 401:
            raise UnauthorizedError(
                pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json())  # type: ignore
            )
        if _response.status_code == 403:
            raise ForbiddenError(pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json()))  # type: ignore
        if _response.status_code == 500:
            raise InternalServerError(
                pydantic_v1.parse_obj_as(types_api_error_ApiError, _response.json())  # type: ignore
            )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise core_api_error_ApiError(status_code=_response.status_code, body=_response.text)
        raise core_api_error_ApiError(status_code=_response.status_code, body=_response_json)
