# 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.pydantic_utilities import parse_obj_as
from .....core.request_options import RequestOptions
from ....commons.errors.entity_not_found_error import EntityNotFoundError
from ....commons.errors.unauthorized_error import UnauthorizedError
from ....commons.types.entity_not_found_error_message import EntityNotFoundErrorMessage
from ....commons.types.schema_id import SchemaId
from ....commons.types.unauthorized_error_message import UnauthorizedErrorMessage
from .errors.schema_validation_http_failure import SchemaValidationHttpFailure
from .types.schema import Schema
from .types.schema_field import SchemaField
from .types.schema_get_multi_response import SchemaGetMultiResponse
from .types.schema_validation_failure import SchemaValidationFailure

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


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

    def get_multi(
        self, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[SchemaGetMultiResponse]:
        """
        Returns all custom schemas.

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

        Returns
        -------
        HttpResponse[SchemaGetMultiResponse]
        """
        _response = self._client_wrapper.httpx_client.request(
            "api/custom-schemas/v1",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="GET",
            request_options=request_options,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        if 200 <= _response.status_code < 300:
            _data = typing.cast(
                SchemaGetMultiResponse,
                parse_obj_as(
                    type_=SchemaGetMultiResponse,  # type: ignore
                    object_=_response_json,
                ),
            )
            return HttpResponse(response=_response, data=_data)
        if "errorName" in _response_json:
            if _response_json["errorName"] == "UnauthorizedError":
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        UnauthorizedErrorMessage,
                        parse_obj_as(
                            type_=UnauthorizedErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def get(
        self, schema_id: SchemaId, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[Schema]:
        """
        Return a custom schema with a given ID.

        Parameters
        ----------
        schema_id : SchemaId

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

        Returns
        -------
        HttpResponse[Schema]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/custom-schemas/v1/{jsonable_encoder(schema_id)}",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="GET",
            request_options=request_options,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        if 200 <= _response.status_code < 300:
            _data = typing.cast(
                Schema,
                parse_obj_as(
                    type_=Schema,  # type: ignore
                    object_=_response_json,
                ),
            )
            return HttpResponse(response=_response, data=_data)
        if "errorName" in _response_json:
            if _response_json["errorName"] == "EntityNotFoundError":
                raise EntityNotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        EntityNotFoundErrorMessage,
                        parse_obj_as(
                            type_=EntityNotFoundErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
            if _response_json["errorName"] == "UnauthorizedError":
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        UnauthorizedErrorMessage,
                        parse_obj_as(
                            type_=UnauthorizedErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def create(
        self,
        *,
        name: str,
        fields: typing.Sequence[SchemaField],
        description: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[Schema]:
        """
        Create custom schema with a set of typed keys. Schema keys can be referenced as inputs in user-configurable rules in the Rules
        Engine, and key-value pairs can be attached to claims via the Encounters API.

        Parameters
        ----------
        name : str

        fields : typing.Sequence[SchemaField]

        description : typing.Optional[str]

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

        Returns
        -------
        HttpResponse[Schema]
        """
        _response = self._client_wrapper.httpx_client.request(
            "api/custom-schemas/v1",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="POST",
            json={
                "name": name,
                "description": description,
                "fields": fields,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        if 200 <= _response.status_code < 300:
            _data = typing.cast(
                Schema,
                parse_obj_as(
                    type_=Schema,  # type: ignore
                    object_=_response_json,
                ),
            )
            return HttpResponse(response=_response, data=_data)
        if "errorName" in _response_json:
            if _response_json["errorName"] == "SchemaValidationHttpFailure":
                raise SchemaValidationHttpFailure(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        SchemaValidationFailure,
                        parse_obj_as(
                            type_=SchemaValidationFailure,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def update(
        self,
        schema_id: SchemaId,
        *,
        name: typing.Optional[str] = OMIT,
        description: typing.Optional[str] = OMIT,
        fields_to_add: typing.Optional[typing.Sequence[SchemaField]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[Schema]:
        """
        Update the name, description, or keys on a preexisting schema.

        Parameters
        ----------
        schema_id : SchemaId

        name : typing.Optional[str]

        description : typing.Optional[str]

        fields_to_add : typing.Optional[typing.Sequence[SchemaField]]
            A list of typed entries to add to schema. Only additive modifications are permitted.

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

        Returns
        -------
        HttpResponse[Schema]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/custom-schemas/v1/{jsonable_encoder(schema_id)}",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="PATCH",
            json={
                "name": name,
                "description": description,
                "fields_to_add": fields_to_add,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        if 200 <= _response.status_code < 300:
            _data = typing.cast(
                Schema,
                parse_obj_as(
                    type_=Schema,  # type: ignore
                    object_=_response_json,
                ),
            )
            return HttpResponse(response=_response, data=_data)
        if "errorName" in _response_json:
            if _response_json["errorName"] == "EntityNotFoundError":
                raise EntityNotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        EntityNotFoundErrorMessage,
                        parse_obj_as(
                            type_=EntityNotFoundErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
            if _response_json["errorName"] == "UnauthorizedError":
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        UnauthorizedErrorMessage,
                        parse_obj_as(
                            type_=UnauthorizedErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
            if _response_json["errorName"] == "SchemaValidationHttpFailure":
                raise SchemaValidationHttpFailure(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        SchemaValidationFailure,
                        parse_obj_as(
                            type_=SchemaValidationFailure,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)


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

    async def get_multi(
        self, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[SchemaGetMultiResponse]:
        """
        Returns all custom schemas.

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

        Returns
        -------
        AsyncHttpResponse[SchemaGetMultiResponse]
        """
        _response = await self._client_wrapper.httpx_client.request(
            "api/custom-schemas/v1",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="GET",
            request_options=request_options,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        if 200 <= _response.status_code < 300:
            _data = typing.cast(
                SchemaGetMultiResponse,
                parse_obj_as(
                    type_=SchemaGetMultiResponse,  # type: ignore
                    object_=_response_json,
                ),
            )
            return AsyncHttpResponse(response=_response, data=_data)
        if "errorName" in _response_json:
            if _response_json["errorName"] == "UnauthorizedError":
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        UnauthorizedErrorMessage,
                        parse_obj_as(
                            type_=UnauthorizedErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def get(
        self, schema_id: SchemaId, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[Schema]:
        """
        Return a custom schema with a given ID.

        Parameters
        ----------
        schema_id : SchemaId

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

        Returns
        -------
        AsyncHttpResponse[Schema]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/custom-schemas/v1/{jsonable_encoder(schema_id)}",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="GET",
            request_options=request_options,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        if 200 <= _response.status_code < 300:
            _data = typing.cast(
                Schema,
                parse_obj_as(
                    type_=Schema,  # type: ignore
                    object_=_response_json,
                ),
            )
            return AsyncHttpResponse(response=_response, data=_data)
        if "errorName" in _response_json:
            if _response_json["errorName"] == "EntityNotFoundError":
                raise EntityNotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        EntityNotFoundErrorMessage,
                        parse_obj_as(
                            type_=EntityNotFoundErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
            if _response_json["errorName"] == "UnauthorizedError":
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        UnauthorizedErrorMessage,
                        parse_obj_as(
                            type_=UnauthorizedErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def create(
        self,
        *,
        name: str,
        fields: typing.Sequence[SchemaField],
        description: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[Schema]:
        """
        Create custom schema with a set of typed keys. Schema keys can be referenced as inputs in user-configurable rules in the Rules
        Engine, and key-value pairs can be attached to claims via the Encounters API.

        Parameters
        ----------
        name : str

        fields : typing.Sequence[SchemaField]

        description : typing.Optional[str]

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

        Returns
        -------
        AsyncHttpResponse[Schema]
        """
        _response = await self._client_wrapper.httpx_client.request(
            "api/custom-schemas/v1",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="POST",
            json={
                "name": name,
                "description": description,
                "fields": fields,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        if 200 <= _response.status_code < 300:
            _data = typing.cast(
                Schema,
                parse_obj_as(
                    type_=Schema,  # type: ignore
                    object_=_response_json,
                ),
            )
            return AsyncHttpResponse(response=_response, data=_data)
        if "errorName" in _response_json:
            if _response_json["errorName"] == "SchemaValidationHttpFailure":
                raise SchemaValidationHttpFailure(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        SchemaValidationFailure,
                        parse_obj_as(
                            type_=SchemaValidationFailure,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def update(
        self,
        schema_id: SchemaId,
        *,
        name: typing.Optional[str] = OMIT,
        description: typing.Optional[str] = OMIT,
        fields_to_add: typing.Optional[typing.Sequence[SchemaField]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[Schema]:
        """
        Update the name, description, or keys on a preexisting schema.

        Parameters
        ----------
        schema_id : SchemaId

        name : typing.Optional[str]

        description : typing.Optional[str]

        fields_to_add : typing.Optional[typing.Sequence[SchemaField]]
            A list of typed entries to add to schema. Only additive modifications are permitted.

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

        Returns
        -------
        AsyncHttpResponse[Schema]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/custom-schemas/v1/{jsonable_encoder(schema_id)}",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="PATCH",
            json={
                "name": name,
                "description": description,
                "fields_to_add": fields_to_add,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        if 200 <= _response.status_code < 300:
            _data = typing.cast(
                Schema,
                parse_obj_as(
                    type_=Schema,  # type: ignore
                    object_=_response_json,
                ),
            )
            return AsyncHttpResponse(response=_response, data=_data)
        if "errorName" in _response_json:
            if _response_json["errorName"] == "EntityNotFoundError":
                raise EntityNotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        EntityNotFoundErrorMessage,
                        parse_obj_as(
                            type_=EntityNotFoundErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
            if _response_json["errorName"] == "UnauthorizedError":
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        UnauthorizedErrorMessage,
                        parse_obj_as(
                            type_=UnauthorizedErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
            if _response_json["errorName"] == "SchemaValidationHttpFailure":
                raise SchemaValidationHttpFailure(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        SchemaValidationFailure,
                        parse_obj_as(
                            type_=SchemaValidationFailure,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
