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

import typing
import uuid
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.unprocessable_entity_error import UnprocessableEntityError
from ....commons.types.entity_not_found_error_message import EntityNotFoundErrorMessage
from ....commons.types.page_token import PageToken
from ....commons.types.sort_direction import SortDirection
from ....commons.types.state import State
from ....commons.types.unprocessable_entity_error_message import UnprocessableEntityErrorMessage
from ..v_2.errors.contract_invalid_expiration_date_http_error import ContractInvalidExpirationDateHttpError
from ..v_2.errors.contract_is_linked_to_fee_schedule_http_error import ContractIsLinkedToFeeScheduleHttpError
from ..v_2.types.contract_invalid_expiration_date_error import ContractInvalidExpirationDateError
from ..v_2.types.contract_is_linked_to_fee_schedule_error import ContractIsLinkedToFeeScheduleError
from ..v_2.types.contract_sort_field import ContractSortField
from ..v_2.types.contract_status import ContractStatus
from .types.contract_create_union import ContractCreateUnion
from .types.contract_id import ContractId
from .types.contract_service_facility import ContractServiceFacility
from .types.contract_service_facility_id import ContractServiceFacilityId
from .types.contract_type import ContractType
from .types.contract_update_union import ContractUpdateUnion
from .types.contract_with_providers_union import ContractWithProvidersUnion
from .types.contracting_provider_id import ContractingProviderId
from .types.contracts_page import ContractsPage
from .types.rendering_providerid import RenderingProviderid

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


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

    def get(
        self, contract_id: ContractId, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[ContractWithProvidersUnion]:
        """
        Parameters
        ----------
        contract_id : ContractId

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

        Returns
        -------
        HttpResponse[ContractWithProvidersUnion]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/contracts/v3/{jsonable_encoder(contract_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(
                ContractWithProvidersUnion,
                parse_obj_as(
                    type_=ContractWithProvidersUnion,  # 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"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def get_multi(
        self,
        *,
        page_token: typing.Optional[PageToken] = None,
        limit: typing.Optional[int] = None,
        type: typing.Optional[ContractType] = None,
        contracting_provider_id: typing.Optional[ContractingProviderId] = None,
        rendering_provider_ids: typing.Optional[
            typing.Union[RenderingProviderid, typing.Sequence[RenderingProviderid]]
        ] = None,
        payer_names: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        states: typing.Optional[typing.Union[State, typing.Sequence[State]]] = None,
        contract_status: typing.Optional[ContractStatus] = None,
        sort: typing.Optional[ContractSortField] = None,
        sort_direction: typing.Optional[SortDirection] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ContractsPage]:
        """
        Parameters
        ----------
        page_token : typing.Optional[PageToken]

        limit : typing.Optional[int]
            Max number of contracts returned. Defaults to 1000. Max is 1000.

        type : typing.Optional[ContractType]
            The type of contract

        contracting_provider_id : typing.Optional[ContractingProviderId]

        rendering_provider_ids : typing.Optional[typing.Union[RenderingProviderid, typing.Sequence[RenderingProviderid]]]

        payer_names : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Filter to contracts that include any of the included payer names.

        states : typing.Optional[typing.Union[State, typing.Sequence[State]]]

        contract_status : typing.Optional[ContractStatus]
            The status of the contract. Defaults to `pending`

        sort : typing.Optional[ContractSortField]
            Potentially sort by a contract related attribute.  Defaults to created_at

        sort_direction : typing.Optional[SortDirection]
            Direction of sort, defaulting to desc

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

        Returns
        -------
        HttpResponse[ContractsPage]
        """
        _response = self._client_wrapper.httpx_client.request(
            "api/contracts/v3",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="GET",
            params={
                "page_token": page_token,
                "limit": limit,
                "type": type,
                "contracting_provider_id": contracting_provider_id,
                "rendering_provider_ids": rendering_provider_ids,
                "payer_names": payer_names,
                "states": states,
                "contract_status": contract_status,
                "sort": sort,
                "sort_direction": sort_direction,
            },
            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(
                ContractsPage,
                parse_obj_as(
                    type_=ContractsPage,  # type: ignore
                    object_=_response_json,
                ),
            )
            return HttpResponse(response=_response, data=_data)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def create(
        self, *, request: ContractCreateUnion, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[ContractWithProvidersUnion]:
        """
        Creates a new contract within the user's current organization

        Parameters
        ----------
        request : ContractCreateUnion

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

        Returns
        -------
        HttpResponse[ContractWithProvidersUnion]
        """
        _response = self._client_wrapper.httpx_client.request(
            "api/contracts/v3",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="POST",
            json=request,
            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(
                ContractWithProvidersUnion,
                parse_obj_as(
                    type_=ContractWithProvidersUnion,  # type: ignore
                    object_=_response_json,
                ),
            )
            return HttpResponse(response=_response, data=_data)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def delete(
        self, contract_id: ContractId, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[None]:
        """
        Parameters
        ----------
        contract_id : ContractId

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

        Returns
        -------
        HttpResponse[None]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/contracts/v3/{jsonable_encoder(contract_id)}",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="DELETE",
            request_options=request_options,
        )
        if 200 <= _response.status_code < 300:
            return HttpResponse(response=_response, data=None)
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        if "errorName" in _response_json:
            if _response_json["errorName"] == "ContractIsLinkedToFeeScheduleHttpError":
                raise ContractIsLinkedToFeeScheduleHttpError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ContractIsLinkedToFeeScheduleError,
                        parse_obj_as(
                            type_=ContractIsLinkedToFeeScheduleError,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def update(
        self,
        contract_id: ContractId,
        *,
        request: ContractUpdateUnion,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ContractWithProvidersUnion]:
        """
        Parameters
        ----------
        contract_id : ContractId

        request : ContractUpdateUnion

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

        Returns
        -------
        HttpResponse[ContractWithProvidersUnion]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/contracts/v3/{jsonable_encoder(contract_id)}",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="PATCH",
            json=request,
            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(
                ContractWithProvidersUnion,
                parse_obj_as(
                    type_=ContractWithProvidersUnion,  # type: ignore
                    object_=_response_json,
                ),
            )
            return HttpResponse(response=_response, data=_data)
        if "errorName" in _response_json:
            if _response_json["errorName"] == "UnprocessableEntityError":
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        UnprocessableEntityErrorMessage,
                        parse_obj_as(
                            type_=UnprocessableEntityErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
            if _response_json["errorName"] == "ContractInvalidExpirationDateHttpError":
                raise ContractInvalidExpirationDateHttpError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ContractInvalidExpirationDateError,
                        parse_obj_as(
                            type_=ContractInvalidExpirationDateError,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def create_contract_service_facility(
        self,
        contract_id: ContractId,
        *,
        service_facility_id: uuid.UUID,
        provider_ids: typing.Set[uuid.UUID],
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ContractServiceFacility]:
        """
        Parameters
        ----------
        contract_id : ContractId

        service_facility_id : uuid.UUID
            The UUID of the service facility

        provider_ids : typing.Set[uuid.UUID]
            The providers who are authorized under the contract

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

        Returns
        -------
        HttpResponse[ContractServiceFacility]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/contracts/v3/{jsonable_encoder(contract_id)}/service-facilities",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="POST",
            json={
                "service_facility_id": service_facility_id,
                "provider_ids": provider_ids,
            },
            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(
                ContractServiceFacility,
                parse_obj_as(
                    type_=ContractServiceFacility,  # type: ignore
                    object_=_response_json,
                ),
            )
            return HttpResponse(response=_response, data=_data)
        if "errorName" in _response_json:
            if _response_json["errorName"] == "UnprocessableEntityError":
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        UnprocessableEntityErrorMessage,
                        parse_obj_as(
                            type_=UnprocessableEntityErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def update_contract_service_facility(
        self,
        contract_id: ContractId,
        contract_service_facility_id: ContractServiceFacilityId,
        *,
        service_facility_id: typing.Optional[uuid.UUID] = OMIT,
        provider_ids: typing.Optional[typing.Set[uuid.UUID]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ContractServiceFacility]:
        """
        Parameters
        ----------
        contract_id : ContractId

        contract_service_facility_id : ContractServiceFacilityId

        service_facility_id : typing.Optional[uuid.UUID]
            The UUID of the service facility

        provider_ids : typing.Optional[typing.Set[uuid.UUID]]
            The providers who are authorized under the contract

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

        Returns
        -------
        HttpResponse[ContractServiceFacility]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/contracts/v3/{jsonable_encoder(contract_id)}/service-facilities/{jsonable_encoder(contract_service_facility_id)}",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="PATCH",
            json={
                "service_facility_id": service_facility_id,
                "provider_ids": provider_ids,
            },
            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(
                ContractServiceFacility,
                parse_obj_as(
                    type_=ContractServiceFacility,  # type: ignore
                    object_=_response_json,
                ),
            )
            return HttpResponse(response=_response, data=_data)
        if "errorName" in _response_json:
            if _response_json["errorName"] == "UnprocessableEntityError":
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        UnprocessableEntityErrorMessage,
                        parse_obj_as(
                            type_=UnprocessableEntityErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)


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

    async def get(
        self, contract_id: ContractId, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[ContractWithProvidersUnion]:
        """
        Parameters
        ----------
        contract_id : ContractId

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

        Returns
        -------
        AsyncHttpResponse[ContractWithProvidersUnion]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/contracts/v3/{jsonable_encoder(contract_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(
                ContractWithProvidersUnion,
                parse_obj_as(
                    type_=ContractWithProvidersUnion,  # 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"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def get_multi(
        self,
        *,
        page_token: typing.Optional[PageToken] = None,
        limit: typing.Optional[int] = None,
        type: typing.Optional[ContractType] = None,
        contracting_provider_id: typing.Optional[ContractingProviderId] = None,
        rendering_provider_ids: typing.Optional[
            typing.Union[RenderingProviderid, typing.Sequence[RenderingProviderid]]
        ] = None,
        payer_names: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        states: typing.Optional[typing.Union[State, typing.Sequence[State]]] = None,
        contract_status: typing.Optional[ContractStatus] = None,
        sort: typing.Optional[ContractSortField] = None,
        sort_direction: typing.Optional[SortDirection] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ContractsPage]:
        """
        Parameters
        ----------
        page_token : typing.Optional[PageToken]

        limit : typing.Optional[int]
            Max number of contracts returned. Defaults to 1000. Max is 1000.

        type : typing.Optional[ContractType]
            The type of contract

        contracting_provider_id : typing.Optional[ContractingProviderId]

        rendering_provider_ids : typing.Optional[typing.Union[RenderingProviderid, typing.Sequence[RenderingProviderid]]]

        payer_names : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Filter to contracts that include any of the included payer names.

        states : typing.Optional[typing.Union[State, typing.Sequence[State]]]

        contract_status : typing.Optional[ContractStatus]
            The status of the contract. Defaults to `pending`

        sort : typing.Optional[ContractSortField]
            Potentially sort by a contract related attribute.  Defaults to created_at

        sort_direction : typing.Optional[SortDirection]
            Direction of sort, defaulting to desc

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

        Returns
        -------
        AsyncHttpResponse[ContractsPage]
        """
        _response = await self._client_wrapper.httpx_client.request(
            "api/contracts/v3",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="GET",
            params={
                "page_token": page_token,
                "limit": limit,
                "type": type,
                "contracting_provider_id": contracting_provider_id,
                "rendering_provider_ids": rendering_provider_ids,
                "payer_names": payer_names,
                "states": states,
                "contract_status": contract_status,
                "sort": sort,
                "sort_direction": sort_direction,
            },
            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(
                ContractsPage,
                parse_obj_as(
                    type_=ContractsPage,  # type: ignore
                    object_=_response_json,
                ),
            )
            return AsyncHttpResponse(response=_response, data=_data)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def create(
        self, *, request: ContractCreateUnion, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[ContractWithProvidersUnion]:
        """
        Creates a new contract within the user's current organization

        Parameters
        ----------
        request : ContractCreateUnion

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

        Returns
        -------
        AsyncHttpResponse[ContractWithProvidersUnion]
        """
        _response = await self._client_wrapper.httpx_client.request(
            "api/contracts/v3",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="POST",
            json=request,
            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(
                ContractWithProvidersUnion,
                parse_obj_as(
                    type_=ContractWithProvidersUnion,  # type: ignore
                    object_=_response_json,
                ),
            )
            return AsyncHttpResponse(response=_response, data=_data)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def delete(
        self, contract_id: ContractId, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[None]:
        """
        Parameters
        ----------
        contract_id : ContractId

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

        Returns
        -------
        AsyncHttpResponse[None]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/contracts/v3/{jsonable_encoder(contract_id)}",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="DELETE",
            request_options=request_options,
        )
        if 200 <= _response.status_code < 300:
            return AsyncHttpResponse(response=_response, data=None)
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        if "errorName" in _response_json:
            if _response_json["errorName"] == "ContractIsLinkedToFeeScheduleHttpError":
                raise ContractIsLinkedToFeeScheduleHttpError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ContractIsLinkedToFeeScheduleError,
                        parse_obj_as(
                            type_=ContractIsLinkedToFeeScheduleError,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def update(
        self,
        contract_id: ContractId,
        *,
        request: ContractUpdateUnion,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ContractWithProvidersUnion]:
        """
        Parameters
        ----------
        contract_id : ContractId

        request : ContractUpdateUnion

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

        Returns
        -------
        AsyncHttpResponse[ContractWithProvidersUnion]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/contracts/v3/{jsonable_encoder(contract_id)}",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="PATCH",
            json=request,
            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(
                ContractWithProvidersUnion,
                parse_obj_as(
                    type_=ContractWithProvidersUnion,  # type: ignore
                    object_=_response_json,
                ),
            )
            return AsyncHttpResponse(response=_response, data=_data)
        if "errorName" in _response_json:
            if _response_json["errorName"] == "UnprocessableEntityError":
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        UnprocessableEntityErrorMessage,
                        parse_obj_as(
                            type_=UnprocessableEntityErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
            if _response_json["errorName"] == "ContractInvalidExpirationDateHttpError":
                raise ContractInvalidExpirationDateHttpError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ContractInvalidExpirationDateError,
                        parse_obj_as(
                            type_=ContractInvalidExpirationDateError,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def create_contract_service_facility(
        self,
        contract_id: ContractId,
        *,
        service_facility_id: uuid.UUID,
        provider_ids: typing.Set[uuid.UUID],
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ContractServiceFacility]:
        """
        Parameters
        ----------
        contract_id : ContractId

        service_facility_id : uuid.UUID
            The UUID of the service facility

        provider_ids : typing.Set[uuid.UUID]
            The providers who are authorized under the contract

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

        Returns
        -------
        AsyncHttpResponse[ContractServiceFacility]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/contracts/v3/{jsonable_encoder(contract_id)}/service-facilities",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="POST",
            json={
                "service_facility_id": service_facility_id,
                "provider_ids": provider_ids,
            },
            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(
                ContractServiceFacility,
                parse_obj_as(
                    type_=ContractServiceFacility,  # type: ignore
                    object_=_response_json,
                ),
            )
            return AsyncHttpResponse(response=_response, data=_data)
        if "errorName" in _response_json:
            if _response_json["errorName"] == "UnprocessableEntityError":
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        UnprocessableEntityErrorMessage,
                        parse_obj_as(
                            type_=UnprocessableEntityErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def update_contract_service_facility(
        self,
        contract_id: ContractId,
        contract_service_facility_id: ContractServiceFacilityId,
        *,
        service_facility_id: typing.Optional[uuid.UUID] = OMIT,
        provider_ids: typing.Optional[typing.Set[uuid.UUID]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ContractServiceFacility]:
        """
        Parameters
        ----------
        contract_id : ContractId

        contract_service_facility_id : ContractServiceFacilityId

        service_facility_id : typing.Optional[uuid.UUID]
            The UUID of the service facility

        provider_ids : typing.Optional[typing.Set[uuid.UUID]]
            The providers who are authorized under the contract

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

        Returns
        -------
        AsyncHttpResponse[ContractServiceFacility]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/contracts/v3/{jsonable_encoder(contract_id)}/service-facilities/{jsonable_encoder(contract_service_facility_id)}",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="PATCH",
            json={
                "service_facility_id": service_facility_id,
                "provider_ids": provider_ids,
            },
            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(
                ContractServiceFacility,
                parse_obj_as(
                    type_=ContractServiceFacility,  # type: ignore
                    object_=_response_json,
                ),
            )
            return AsyncHttpResponse(response=_response, data=_data)
        if "errorName" in _response_json:
            if _response_json["errorName"] == "UnprocessableEntityError":
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        UnprocessableEntityErrorMessage,
                        parse_obj_as(
                            type_=UnprocessableEntityErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
