# 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 ..core.serialization import convert_and_respect_annotation_metadata
from .errors.bad_request_error import BadRequestError
from .errors.internal_server_error import InternalServerError
from .errors.not_found_error import NotFoundError
from .errors.unauthorized_error import UnauthorizedError
from .types.fhir_bundle import FhirBundle
from .types.fhir_bundle_entry_item import FhirBundleEntryItem
from .types.fhir_patch_request_body_item import FhirPatchRequestBodyItem
from .types.fhir_resource import FhirResource
from .types.fhir_resource_meta import FhirResourceMeta
from .types.fhir_search_response import FhirSearchResponse

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


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

    def search(
        self,
        fhir_provider_id: str,
        fhir_path: str,
        *,
        query_parameters: typing.Optional[typing.Dict[str, typing.Optional[str]]] = None,
        phenoml_on_behalf_of: typing.Optional[str] = None,
        phenoml_fhir_provider: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[FhirSearchResponse]:
        """
        Retrieves FHIR resources from the specified provider. Supports both individual resource retrieval and search operations based on the FHIR path and query parameters.

        The request is proxied to the configured FHIR server with appropriate authentication headers.

        Parameters
        ----------
        fhir_provider_id : str
            The ID of the FHIR provider to use. Can be either:
            - A UUID representing the provider ID
            - A provider name (legacy support - will just use the most recently updated provider with this name)

        fhir_path : str
            The FHIR resource path to operate on. This follows FHIR RESTful API conventions.
            Examples:
            - "Patient" (for resource type operations)
            - "Patient/123" (for specific resource operations)
            - "Patient/123/_history" (for history operations)

        query_parameters : typing.Optional[typing.Dict[str, typing.Optional[str]]]
            FHIR-compliant query parameters for search operations. Supports standard FHIR search parameters including:
            - Resource-specific search parameters (e.g., name for Patient, status for Observation)
            - Common search parameters (_id, _lastUpdated, _tag, _profile, _security, _text, _content, _filter)
            - Result parameters (_count, _offset, _sort, _include, _revinclude, _summary, _elements)
            - Search prefixes for dates, numbers, quantities (eq, ne, gt, ge, lt, le, sa, eb, ap)

        phenoml_on_behalf_of : typing.Optional[str]
            Optional header for on-behalf-of authentication. Used when making requests on behalf of another user or entity.
            Must be in the format: Patient/{uuid} or Practitioner/{uuid}

        phenoml_fhir_provider : typing.Optional[str]
            Optional header for FHIR provider authentication. Contains credentials in the format {fhir_provider_id}:{oauth2_token}.
            Multiple FHIR provider integrations can be provided as comma-separated values.

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

        Returns
        -------
        HttpResponse[FhirSearchResponse]
            Successfully retrieved FHIR resource(s)
        """
        _response = self._client_wrapper.httpx_client.request(
            f"fhir-provider/{jsonable_encoder(fhir_provider_id)}/fhir/{jsonable_encoder(fhir_path)}",
            method="GET",
            params={
                "query_parameters": query_parameters,
            },
            headers={
                "X-Phenoml-On-Behalf-Of": str(phenoml_on_behalf_of) if phenoml_on_behalf_of is not None else None,
                "X-Phenoml-Fhir-Provider": str(phenoml_fhir_provider) if phenoml_fhir_provider is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    FhirSearchResponse,
                    parse_obj_as(
                        type_=FhirSearchResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def create(
        self,
        fhir_provider_id: str,
        fhir_path: str,
        *,
        resource_type: str,
        phenoml_on_behalf_of: typing.Optional[str] = None,
        phenoml_fhir_provider: typing.Optional[str] = None,
        id: typing.Optional[str] = OMIT,
        meta: typing.Optional[FhirResourceMeta] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[FhirResource]:
        """
        Creates a new FHIR resource on the specified provider. The request body should contain a valid FHIR resource in JSON format.

        The request is proxied to the configured FHIR server with appropriate authentication headers.

        Parameters
        ----------
        fhir_provider_id : str
            The ID of the FHIR provider to use. Can be either:
            - A UUID representing the provider ID
            - A provider name (legacy support - will just use the most recently updated provider with this name)

        fhir_path : str
            The FHIR resource path to operate on. This follows FHIR RESTful API conventions.
            Examples:
            - "Patient" (for resource type operations)
            - "Patient/123" (for specific resource operations)
            - "Patient/123/_history" (for history operations)

        resource_type : str
            The type of FHIR resource (e.g., Patient, Observation, etc.)

        phenoml_on_behalf_of : typing.Optional[str]
            Optional header for on-behalf-of authentication. Used when making requests on behalf of another user or entity.
            Must be in the format: Patient/{uuid} or Practitioner/{uuid}

        phenoml_fhir_provider : typing.Optional[str]
            Optional header for FHIR provider authentication. Contains credentials in the format {fhir_provider_id}:{oauth2_token}.
            Multiple FHIR provider integrations can be provided as comma-separated values.

        id : typing.Optional[str]
            Logical ID of the resource

        meta : typing.Optional[FhirResourceMeta]
            Metadata about the resource

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

        Returns
        -------
        HttpResponse[FhirResource]
            Resource created successfully
        """
        _response = self._client_wrapper.httpx_client.request(
            f"fhir-provider/{jsonable_encoder(fhir_provider_id)}/fhir/{jsonable_encoder(fhir_path)}",
            method="POST",
            json={
                "resourceType": resource_type,
                "id": id,
                "meta": convert_and_respect_annotation_metadata(
                    object_=meta, annotation=FhirResourceMeta, direction="write"
                ),
            },
            headers={
                "content-type": "application/fhir+json",
                "X-Phenoml-On-Behalf-Of": str(phenoml_on_behalf_of) if phenoml_on_behalf_of is not None else None,
                "X-Phenoml-Fhir-Provider": str(phenoml_fhir_provider) if phenoml_fhir_provider is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    FhirResource,
                    parse_obj_as(
                        type_=FhirResource,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def upsert(
        self,
        fhir_provider_id: str,
        fhir_path: str,
        *,
        resource_type: str,
        phenoml_on_behalf_of: typing.Optional[str] = None,
        phenoml_fhir_provider: typing.Optional[str] = None,
        id: typing.Optional[str] = OMIT,
        meta: typing.Optional[FhirResourceMeta] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[FhirResource]:
        """
        Creates or updates a FHIR resource on the specified provider. If the resource exists, it will be updated; otherwise, it will be created.

        The request is proxied to the configured FHIR server with appropriate authentication headers.

        Parameters
        ----------
        fhir_provider_id : str
            The ID of the FHIR provider to use. Can be either:
            - A UUID representing the provider ID
            - A provider name (legacy support - will just use the most recently updated provider with this name)

        fhir_path : str
            The FHIR resource path to operate on. This follows FHIR RESTful API conventions.
            Examples:
            - "Patient" (for resource type operations)
            - "Patient/123" (for specific resource operations)
            - "Patient/123/_history" (for history operations)

        resource_type : str
            The type of FHIR resource (e.g., Patient, Observation, etc.)

        phenoml_on_behalf_of : typing.Optional[str]
            Optional header for on-behalf-of authentication. Used when making requests on behalf of another user or entity.
            Must be in the format: Patient/{uuid} or Practitioner/{uuid}

        phenoml_fhir_provider : typing.Optional[str]
            Optional header for FHIR provider authentication. Contains credentials in the format {fhir_provider_id}:{oauth2_token}.
            Multiple FHIR provider integrations can be provided as comma-separated values.

        id : typing.Optional[str]
            Logical ID of the resource

        meta : typing.Optional[FhirResourceMeta]
            Metadata about the resource

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

        Returns
        -------
        HttpResponse[FhirResource]
            Resource upserted successfully
        """
        _response = self._client_wrapper.httpx_client.request(
            f"fhir-provider/{jsonable_encoder(fhir_provider_id)}/fhir/{jsonable_encoder(fhir_path)}",
            method="PUT",
            json={
                "resourceType": resource_type,
                "id": id,
                "meta": convert_and_respect_annotation_metadata(
                    object_=meta, annotation=FhirResourceMeta, direction="write"
                ),
            },
            headers={
                "content-type": "application/fhir+json",
                "X-Phenoml-On-Behalf-Of": str(phenoml_on_behalf_of) if phenoml_on_behalf_of is not None else None,
                "X-Phenoml-Fhir-Provider": str(phenoml_fhir_provider) if phenoml_fhir_provider is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    FhirResource,
                    parse_obj_as(
                        type_=FhirResource,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def delete(
        self,
        fhir_provider_id: str,
        fhir_path: str,
        *,
        phenoml_on_behalf_of: typing.Optional[str] = None,
        phenoml_fhir_provider: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[typing.Dict[str, typing.Optional[typing.Any]]]:
        """
        Deletes a FHIR resource from the specified provider.

        The request is proxied to the configured FHIR server with appropriate authentication headers.

        Parameters
        ----------
        fhir_provider_id : str
            The ID of the FHIR provider to use. Can be either:
            - A UUID representing the provider ID
            - A provider name (legacy support - will just use the most recently updated provider with this name)

        fhir_path : str
            The FHIR resource path to operate on. This follows FHIR RESTful API conventions.
            Examples:
            - "Patient" (for resource type operations)
            - "Patient/123" (for specific resource operations)
            - "Patient/123/_history" (for history operations)

        phenoml_on_behalf_of : typing.Optional[str]
            Optional header for on-behalf-of authentication. Used when making requests on behalf of another user or entity.
            Must be in the format: Patient/{uuid} or Practitioner/{uuid}

        phenoml_fhir_provider : typing.Optional[str]
            Optional header for FHIR provider authentication. Contains credentials in the format {fhir_provider_id}:{oauth2_token}.
            Multiple FHIR provider integrations can be provided as comma-separated values.

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

        Returns
        -------
        HttpResponse[typing.Dict[str, typing.Optional[typing.Any]]]
            Resource deleted successfully
        """
        _response = self._client_wrapper.httpx_client.request(
            f"fhir-provider/{jsonable_encoder(fhir_provider_id)}/fhir/{jsonable_encoder(fhir_path)}",
            method="DELETE",
            headers={
                "X-Phenoml-On-Behalf-Of": str(phenoml_on_behalf_of) if phenoml_on_behalf_of is not None else None,
                "X-Phenoml-Fhir-Provider": str(phenoml_fhir_provider) if phenoml_fhir_provider is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Dict[str, typing.Optional[typing.Any]],
                    parse_obj_as(
                        type_=typing.Dict[str, typing.Optional[typing.Any]],  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def patch(
        self,
        fhir_provider_id: str,
        fhir_path: str,
        *,
        request: typing.Sequence[FhirPatchRequestBodyItem],
        phenoml_on_behalf_of: typing.Optional[str] = None,
        phenoml_fhir_provider: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[FhirResource]:
        """
        Partially updates a FHIR resource on the specified provider using JSON Patch operations as defined in RFC 6902.

        The request body should contain an array of JSON Patch operations. Each operation specifies:
        - `op`: The operation type (add, remove, replace, move, copy, test)
        - `path`: JSON Pointer to the target location in the resource
        - `value`: The value to use (required for add, replace, and test operations)

        The request is proxied to the configured FHIR server with appropriate authentication headers.

        Parameters
        ----------
        fhir_provider_id : str
            The ID of the FHIR provider to use. Can be either:
            - A UUID representing the provider ID
            - A provider name (legacy support - will just use the most recently updated provider with this name)

        fhir_path : str
            The FHIR resource path to operate on. This follows FHIR RESTful API conventions.
            Examples:
            - "Patient" (for resource type operations)
            - "Patient/123" (for specific resource operations)
            - "Patient/123/_history" (for history operations)

        request : typing.Sequence[FhirPatchRequestBodyItem]

        phenoml_on_behalf_of : typing.Optional[str]
            Optional header for on-behalf-of authentication. Used when making requests on behalf of another user or entity.
            Must be in the format: Patient/{uuid} or Practitioner/{uuid}

        phenoml_fhir_provider : typing.Optional[str]
            Optional header for FHIR provider authentication. Contains credentials in the format {fhir_provider_id}:{oauth2_token}.
            Multiple FHIR provider integrations can be provided as comma-separated values.

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

        Returns
        -------
        HttpResponse[FhirResource]
            Resource patched successfully
        """
        _response = self._client_wrapper.httpx_client.request(
            f"fhir-provider/{jsonable_encoder(fhir_provider_id)}/fhir/{jsonable_encoder(fhir_path)}",
            method="PATCH",
            json=convert_and_respect_annotation_metadata(
                object_=request, annotation=typing.Sequence[FhirPatchRequestBodyItem], direction="write"
            ),
            headers={
                "content-type": "application/json-patch+json",
                "X-Phenoml-On-Behalf-Of": str(phenoml_on_behalf_of) if phenoml_on_behalf_of is not None else None,
                "X-Phenoml-Fhir-Provider": str(phenoml_fhir_provider) if phenoml_fhir_provider is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    FhirResource,
                    parse_obj_as(
                        type_=FhirResource,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def execute_bundle(
        self,
        fhir_provider_id: str,
        *,
        entry: typing.Sequence[FhirBundleEntryItem],
        phenoml_on_behalf_of: typing.Optional[str] = None,
        phenoml_fhir_provider: typing.Optional[str] = None,
        total: typing.Optional[int] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[FhirBundle]:
        """
        Executes a FHIR Bundle transaction or batch operation on the specified provider. This allows multiple FHIR resources to be processed in a single request.

        The request body should contain a valid FHIR Bundle resource with transaction or batch type.

        The request is proxied to the configured FHIR server with appropriate authentication headers.

        Parameters
        ----------
        fhir_provider_id : str
            The ID of the FHIR provider to use. Can be either:
            - A UUID representing the provider ID
            - A provider name (legacy support - will just use the most recently updated provider with this name)

        entry : typing.Sequence[FhirBundleEntryItem]
            Array of bundle entries containing resources or operation results

        phenoml_on_behalf_of : typing.Optional[str]
            Optional header for on-behalf-of authentication. Used when making requests on behalf of another user or entity.
            Must be in the format: Patient/{uuid} or Practitioner/{uuid}

        phenoml_fhir_provider : typing.Optional[str]
            Optional header for FHIR provider authentication. Contains credentials in the format {fhir_provider_id}:{oauth2_token}.
            Multiple FHIR provider integrations can be provided as comma-separated values.

        total : typing.Optional[int]
            Total number of resources that match the search criteria.
            Optional field as not all FHIR servers include it (e.g., Medplum).

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

        Returns
        -------
        HttpResponse[FhirBundle]
            Bundle executed successfully
        """
        _response = self._client_wrapper.httpx_client.request(
            f"fhir-provider/{jsonable_encoder(fhir_provider_id)}/fhir",
            method="POST",
            json={
                "total": total,
                "entry": convert_and_respect_annotation_metadata(
                    object_=entry, annotation=typing.Sequence[FhirBundleEntryItem], direction="write"
                ),
                "resourceType": "Bundle",
            },
            headers={
                "content-type": "application/fhir+json",
                "X-Phenoml-On-Behalf-Of": str(phenoml_on_behalf_of) if phenoml_on_behalf_of is not None else None,
                "X-Phenoml-Fhir-Provider": str(phenoml_fhir_provider) if phenoml_fhir_provider is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    FhirBundle,
                    parse_obj_as(
                        type_=FhirBundle,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)


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

    async def search(
        self,
        fhir_provider_id: str,
        fhir_path: str,
        *,
        query_parameters: typing.Optional[typing.Dict[str, typing.Optional[str]]] = None,
        phenoml_on_behalf_of: typing.Optional[str] = None,
        phenoml_fhir_provider: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[FhirSearchResponse]:
        """
        Retrieves FHIR resources from the specified provider. Supports both individual resource retrieval and search operations based on the FHIR path and query parameters.

        The request is proxied to the configured FHIR server with appropriate authentication headers.

        Parameters
        ----------
        fhir_provider_id : str
            The ID of the FHIR provider to use. Can be either:
            - A UUID representing the provider ID
            - A provider name (legacy support - will just use the most recently updated provider with this name)

        fhir_path : str
            The FHIR resource path to operate on. This follows FHIR RESTful API conventions.
            Examples:
            - "Patient" (for resource type operations)
            - "Patient/123" (for specific resource operations)
            - "Patient/123/_history" (for history operations)

        query_parameters : typing.Optional[typing.Dict[str, typing.Optional[str]]]
            FHIR-compliant query parameters for search operations. Supports standard FHIR search parameters including:
            - Resource-specific search parameters (e.g., name for Patient, status for Observation)
            - Common search parameters (_id, _lastUpdated, _tag, _profile, _security, _text, _content, _filter)
            - Result parameters (_count, _offset, _sort, _include, _revinclude, _summary, _elements)
            - Search prefixes for dates, numbers, quantities (eq, ne, gt, ge, lt, le, sa, eb, ap)

        phenoml_on_behalf_of : typing.Optional[str]
            Optional header for on-behalf-of authentication. Used when making requests on behalf of another user or entity.
            Must be in the format: Patient/{uuid} or Practitioner/{uuid}

        phenoml_fhir_provider : typing.Optional[str]
            Optional header for FHIR provider authentication. Contains credentials in the format {fhir_provider_id}:{oauth2_token}.
            Multiple FHIR provider integrations can be provided as comma-separated values.

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

        Returns
        -------
        AsyncHttpResponse[FhirSearchResponse]
            Successfully retrieved FHIR resource(s)
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"fhir-provider/{jsonable_encoder(fhir_provider_id)}/fhir/{jsonable_encoder(fhir_path)}",
            method="GET",
            params={
                "query_parameters": query_parameters,
            },
            headers={
                "X-Phenoml-On-Behalf-Of": str(phenoml_on_behalf_of) if phenoml_on_behalf_of is not None else None,
                "X-Phenoml-Fhir-Provider": str(phenoml_fhir_provider) if phenoml_fhir_provider is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    FhirSearchResponse,
                    parse_obj_as(
                        type_=FhirSearchResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def create(
        self,
        fhir_provider_id: str,
        fhir_path: str,
        *,
        resource_type: str,
        phenoml_on_behalf_of: typing.Optional[str] = None,
        phenoml_fhir_provider: typing.Optional[str] = None,
        id: typing.Optional[str] = OMIT,
        meta: typing.Optional[FhirResourceMeta] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[FhirResource]:
        """
        Creates a new FHIR resource on the specified provider. The request body should contain a valid FHIR resource in JSON format.

        The request is proxied to the configured FHIR server with appropriate authentication headers.

        Parameters
        ----------
        fhir_provider_id : str
            The ID of the FHIR provider to use. Can be either:
            - A UUID representing the provider ID
            - A provider name (legacy support - will just use the most recently updated provider with this name)

        fhir_path : str
            The FHIR resource path to operate on. This follows FHIR RESTful API conventions.
            Examples:
            - "Patient" (for resource type operations)
            - "Patient/123" (for specific resource operations)
            - "Patient/123/_history" (for history operations)

        resource_type : str
            The type of FHIR resource (e.g., Patient, Observation, etc.)

        phenoml_on_behalf_of : typing.Optional[str]
            Optional header for on-behalf-of authentication. Used when making requests on behalf of another user or entity.
            Must be in the format: Patient/{uuid} or Practitioner/{uuid}

        phenoml_fhir_provider : typing.Optional[str]
            Optional header for FHIR provider authentication. Contains credentials in the format {fhir_provider_id}:{oauth2_token}.
            Multiple FHIR provider integrations can be provided as comma-separated values.

        id : typing.Optional[str]
            Logical ID of the resource

        meta : typing.Optional[FhirResourceMeta]
            Metadata about the resource

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

        Returns
        -------
        AsyncHttpResponse[FhirResource]
            Resource created successfully
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"fhir-provider/{jsonable_encoder(fhir_provider_id)}/fhir/{jsonable_encoder(fhir_path)}",
            method="POST",
            json={
                "resourceType": resource_type,
                "id": id,
                "meta": convert_and_respect_annotation_metadata(
                    object_=meta, annotation=FhirResourceMeta, direction="write"
                ),
            },
            headers={
                "content-type": "application/fhir+json",
                "X-Phenoml-On-Behalf-Of": str(phenoml_on_behalf_of) if phenoml_on_behalf_of is not None else None,
                "X-Phenoml-Fhir-Provider": str(phenoml_fhir_provider) if phenoml_fhir_provider is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    FhirResource,
                    parse_obj_as(
                        type_=FhirResource,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def upsert(
        self,
        fhir_provider_id: str,
        fhir_path: str,
        *,
        resource_type: str,
        phenoml_on_behalf_of: typing.Optional[str] = None,
        phenoml_fhir_provider: typing.Optional[str] = None,
        id: typing.Optional[str] = OMIT,
        meta: typing.Optional[FhirResourceMeta] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[FhirResource]:
        """
        Creates or updates a FHIR resource on the specified provider. If the resource exists, it will be updated; otherwise, it will be created.

        The request is proxied to the configured FHIR server with appropriate authentication headers.

        Parameters
        ----------
        fhir_provider_id : str
            The ID of the FHIR provider to use. Can be either:
            - A UUID representing the provider ID
            - A provider name (legacy support - will just use the most recently updated provider with this name)

        fhir_path : str
            The FHIR resource path to operate on. This follows FHIR RESTful API conventions.
            Examples:
            - "Patient" (for resource type operations)
            - "Patient/123" (for specific resource operations)
            - "Patient/123/_history" (for history operations)

        resource_type : str
            The type of FHIR resource (e.g., Patient, Observation, etc.)

        phenoml_on_behalf_of : typing.Optional[str]
            Optional header for on-behalf-of authentication. Used when making requests on behalf of another user or entity.
            Must be in the format: Patient/{uuid} or Practitioner/{uuid}

        phenoml_fhir_provider : typing.Optional[str]
            Optional header for FHIR provider authentication. Contains credentials in the format {fhir_provider_id}:{oauth2_token}.
            Multiple FHIR provider integrations can be provided as comma-separated values.

        id : typing.Optional[str]
            Logical ID of the resource

        meta : typing.Optional[FhirResourceMeta]
            Metadata about the resource

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

        Returns
        -------
        AsyncHttpResponse[FhirResource]
            Resource upserted successfully
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"fhir-provider/{jsonable_encoder(fhir_provider_id)}/fhir/{jsonable_encoder(fhir_path)}",
            method="PUT",
            json={
                "resourceType": resource_type,
                "id": id,
                "meta": convert_and_respect_annotation_metadata(
                    object_=meta, annotation=FhirResourceMeta, direction="write"
                ),
            },
            headers={
                "content-type": "application/fhir+json",
                "X-Phenoml-On-Behalf-Of": str(phenoml_on_behalf_of) if phenoml_on_behalf_of is not None else None,
                "X-Phenoml-Fhir-Provider": str(phenoml_fhir_provider) if phenoml_fhir_provider is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    FhirResource,
                    parse_obj_as(
                        type_=FhirResource,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def delete(
        self,
        fhir_provider_id: str,
        fhir_path: str,
        *,
        phenoml_on_behalf_of: typing.Optional[str] = None,
        phenoml_fhir_provider: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[typing.Dict[str, typing.Optional[typing.Any]]]:
        """
        Deletes a FHIR resource from the specified provider.

        The request is proxied to the configured FHIR server with appropriate authentication headers.

        Parameters
        ----------
        fhir_provider_id : str
            The ID of the FHIR provider to use. Can be either:
            - A UUID representing the provider ID
            - A provider name (legacy support - will just use the most recently updated provider with this name)

        fhir_path : str
            The FHIR resource path to operate on. This follows FHIR RESTful API conventions.
            Examples:
            - "Patient" (for resource type operations)
            - "Patient/123" (for specific resource operations)
            - "Patient/123/_history" (for history operations)

        phenoml_on_behalf_of : typing.Optional[str]
            Optional header for on-behalf-of authentication. Used when making requests on behalf of another user or entity.
            Must be in the format: Patient/{uuid} or Practitioner/{uuid}

        phenoml_fhir_provider : typing.Optional[str]
            Optional header for FHIR provider authentication. Contains credentials in the format {fhir_provider_id}:{oauth2_token}.
            Multiple FHIR provider integrations can be provided as comma-separated values.

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

        Returns
        -------
        AsyncHttpResponse[typing.Dict[str, typing.Optional[typing.Any]]]
            Resource deleted successfully
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"fhir-provider/{jsonable_encoder(fhir_provider_id)}/fhir/{jsonable_encoder(fhir_path)}",
            method="DELETE",
            headers={
                "X-Phenoml-On-Behalf-Of": str(phenoml_on_behalf_of) if phenoml_on_behalf_of is not None else None,
                "X-Phenoml-Fhir-Provider": str(phenoml_fhir_provider) if phenoml_fhir_provider is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Dict[str, typing.Optional[typing.Any]],
                    parse_obj_as(
                        type_=typing.Dict[str, typing.Optional[typing.Any]],  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def patch(
        self,
        fhir_provider_id: str,
        fhir_path: str,
        *,
        request: typing.Sequence[FhirPatchRequestBodyItem],
        phenoml_on_behalf_of: typing.Optional[str] = None,
        phenoml_fhir_provider: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[FhirResource]:
        """
        Partially updates a FHIR resource on the specified provider using JSON Patch operations as defined in RFC 6902.

        The request body should contain an array of JSON Patch operations. Each operation specifies:
        - `op`: The operation type (add, remove, replace, move, copy, test)
        - `path`: JSON Pointer to the target location in the resource
        - `value`: The value to use (required for add, replace, and test operations)

        The request is proxied to the configured FHIR server with appropriate authentication headers.

        Parameters
        ----------
        fhir_provider_id : str
            The ID of the FHIR provider to use. Can be either:
            - A UUID representing the provider ID
            - A provider name (legacy support - will just use the most recently updated provider with this name)

        fhir_path : str
            The FHIR resource path to operate on. This follows FHIR RESTful API conventions.
            Examples:
            - "Patient" (for resource type operations)
            - "Patient/123" (for specific resource operations)
            - "Patient/123/_history" (for history operations)

        request : typing.Sequence[FhirPatchRequestBodyItem]

        phenoml_on_behalf_of : typing.Optional[str]
            Optional header for on-behalf-of authentication. Used when making requests on behalf of another user or entity.
            Must be in the format: Patient/{uuid} or Practitioner/{uuid}

        phenoml_fhir_provider : typing.Optional[str]
            Optional header for FHIR provider authentication. Contains credentials in the format {fhir_provider_id}:{oauth2_token}.
            Multiple FHIR provider integrations can be provided as comma-separated values.

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

        Returns
        -------
        AsyncHttpResponse[FhirResource]
            Resource patched successfully
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"fhir-provider/{jsonable_encoder(fhir_provider_id)}/fhir/{jsonable_encoder(fhir_path)}",
            method="PATCH",
            json=convert_and_respect_annotation_metadata(
                object_=request, annotation=typing.Sequence[FhirPatchRequestBodyItem], direction="write"
            ),
            headers={
                "content-type": "application/json-patch+json",
                "X-Phenoml-On-Behalf-Of": str(phenoml_on_behalf_of) if phenoml_on_behalf_of is not None else None,
                "X-Phenoml-Fhir-Provider": str(phenoml_fhir_provider) if phenoml_fhir_provider is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    FhirResource,
                    parse_obj_as(
                        type_=FhirResource,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def execute_bundle(
        self,
        fhir_provider_id: str,
        *,
        entry: typing.Sequence[FhirBundleEntryItem],
        phenoml_on_behalf_of: typing.Optional[str] = None,
        phenoml_fhir_provider: typing.Optional[str] = None,
        total: typing.Optional[int] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[FhirBundle]:
        """
        Executes a FHIR Bundle transaction or batch operation on the specified provider. This allows multiple FHIR resources to be processed in a single request.

        The request body should contain a valid FHIR Bundle resource with transaction or batch type.

        The request is proxied to the configured FHIR server with appropriate authentication headers.

        Parameters
        ----------
        fhir_provider_id : str
            The ID of the FHIR provider to use. Can be either:
            - A UUID representing the provider ID
            - A provider name (legacy support - will just use the most recently updated provider with this name)

        entry : typing.Sequence[FhirBundleEntryItem]
            Array of bundle entries containing resources or operation results

        phenoml_on_behalf_of : typing.Optional[str]
            Optional header for on-behalf-of authentication. Used when making requests on behalf of another user or entity.
            Must be in the format: Patient/{uuid} or Practitioner/{uuid}

        phenoml_fhir_provider : typing.Optional[str]
            Optional header for FHIR provider authentication. Contains credentials in the format {fhir_provider_id}:{oauth2_token}.
            Multiple FHIR provider integrations can be provided as comma-separated values.

        total : typing.Optional[int]
            Total number of resources that match the search criteria.
            Optional field as not all FHIR servers include it (e.g., Medplum).

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

        Returns
        -------
        AsyncHttpResponse[FhirBundle]
            Bundle executed successfully
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"fhir-provider/{jsonable_encoder(fhir_provider_id)}/fhir",
            method="POST",
            json={
                "total": total,
                "entry": convert_and_respect_annotation_metadata(
                    object_=entry, annotation=typing.Sequence[FhirBundleEntryItem], direction="write"
                ),
                "resourceType": "Bundle",
            },
            headers={
                "content-type": "application/fhir+json",
                "X-Phenoml-On-Behalf-Of": str(phenoml_on_behalf_of) if phenoml_on_behalf_of is not None else None,
                "X-Phenoml-Fhir-Provider": str(phenoml_fhir_provider) if phenoml_fhir_provider is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    FhirBundle,
                    parse_obj_as(
                        type_=FhirBundle,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
