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

import datetime as dt
import typing
from json.decoder import JSONDecodeError

from .......core.api_error import ApiError
from .......core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from .......core.datetime_utils import serialize_datetime
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 ....common.errors.bad_request_error import BadRequestError
from ....common.errors.not_found_error import NotFoundError
from ....common.errors.version_conflict_error import VersionConflictError
from ....common.types.coverage_id import CoverageId
from ....common.types.error_base_4_xx import ErrorBase4Xx
from ....common.types.page_token import PageToken
from ....common.types.payer_plan_group_id import PayerPlanGroupId
from ....common.types.sort_direction import SortDirection
from ....common.types.version_conflict_error_body import VersionConflictErrorBody
from ....eligibility_checks.resources.v_1.types.eligibility_check_metadata import EligibilityCheckMetadata
from .types.coverage import Coverage
from .types.coverage_eligibility_check_response import CoverageEligibilityCheckResponse
from .types.coverages_page import CoveragesPage
from .types.mutable_coverage import MutableCoverage
from .types.payer_plan_group_fields import PayerPlanGroupFields
from .types.service_type_code import ServiceTypeCode

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


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

    def create(
        self, *, request: MutableCoverage, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[Coverage]:
        """
        Creates a new Coverage. A Coverage provides the high-level identifiers and descriptors of a specific insurance plan for a specific individual - typically the information you can find on an insurance card. Additionally a coverage will include detailed benefits information covered by the specific plan for the individual.

        Parameters
        ----------
        request : MutableCoverage

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

        Returns
        -------
        HttpResponse[Coverage]
        """
        _response = self._client_wrapper.httpx_client.request(
            "coverages/v1",
            base_url=self._client_wrapper.get_environment().pre_encounter,
            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(
                Coverage,
                parse_obj_as(
                    type_=Coverage,  # 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 update(
        self,
        id: CoverageId,
        version: str,
        *,
        request: MutableCoverage,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[Coverage]:
        """
        Updates a Coverage. The path must contain the next version number to prevent race conditions. For example, if the current version of the coverage is n, you will need to send a request to this endpoint with `/{id}/n+1` to update the coverage. Updating historic versions is not supported.

        Parameters
        ----------
        id : CoverageId

        version : str

        request : MutableCoverage

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

        Returns
        -------
        HttpResponse[Coverage]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"coverages/v1/{jsonable_encoder(id)}/{jsonable_encoder(version)}",
            base_url=self._client_wrapper.get_environment().pre_encounter,
            method="PUT",
            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(
                Coverage,
                parse_obj_as(
                    type_=Coverage,  # type: ignore
                    object_=_response_json,
                ),
            )
            return HttpResponse(response=_response, data=_data)
        if "errorName" in _response_json:
            if _response_json["errorName"] == "NotFoundError":
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorBase4Xx,
                        parse_obj_as(
                            type_=ErrorBase4Xx,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
            if _response_json["errorName"] == "VersionConflictError":
                raise VersionConflictError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        VersionConflictErrorBody,
                        parse_obj_as(
                            type_=VersionConflictErrorBody,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def get_multi_paginated(
        self,
        *,
        patient_id: typing.Optional[str] = None,
        payer_plan_group_id: typing.Optional[str] = None,
        page_token: typing.Optional[PageToken] = None,
        limit: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[CoveragesPage]:
        """
        Returns a page of Coverages based on the search criteria.

        Parameters
        ----------
        patient_id : typing.Optional[str]

        payer_plan_group_id : typing.Optional[str]

        page_token : typing.Optional[PageToken]

        limit : typing.Optional[int]
            Must be between 0 and 1000. Defaults to 100

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

        Returns
        -------
        HttpResponse[CoveragesPage]
        """
        _response = self._client_wrapper.httpx_client.request(
            "coverages/v1/get-multi-paginated",
            base_url=self._client_wrapper.get_environment().pre_encounter,
            method="GET",
            params={
                "patient_id": patient_id,
                "payer_plan_group_id": payer_plan_group_id,
                "page_token": page_token,
                "limit": limit,
            },
            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(
                CoveragesPage,
                parse_obj_as(
                    type_=CoveragesPage,  # type: ignore
                    object_=_response_json,
                ),
            )
            return HttpResponse(response=_response, data=_data)
        if "errorName" in _response_json:
            if _response_json["errorName"] == "BadRequestError":
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorBase4Xx,
                        parse_obj_as(
                            type_=ErrorBase4Xx,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def get(self, id: CoverageId, *, request_options: typing.Optional[RequestOptions] = None) -> HttpResponse[Coverage]:
        """
        gets a specific Coverage

        Parameters
        ----------
        id : CoverageId

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

        Returns
        -------
        HttpResponse[Coverage]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"coverages/v1/{jsonable_encoder(id)}",
            base_url=self._client_wrapper.get_environment().pre_encounter,
            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(
                Coverage,
                parse_obj_as(
                    type_=Coverage,  # 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 get_history(
        self,
        id: CoverageId,
        *,
        start: typing.Optional[dt.date] = None,
        end: typing.Optional[dt.date] = None,
        non_auto_updated_coverages_only: typing.Optional[bool] = None,
        sort_direction: typing.Optional[SortDirection] = None,
        limit: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[typing.List[Coverage]]:
        """
        Gets a coverage's history. Full history is returned if no filters are
        defined. The return list is ordered by version, defaulting to ascending.

        Parameters
        ----------
        id : CoverageId

        start : typing.Optional[dt.date]

        end : typing.Optional[dt.date]

        non_auto_updated_coverages_only : typing.Optional[bool]
            If true, only returns coverages that have NOT been auto-updated by the system.

        sort_direction : typing.Optional[SortDirection]
            Defaults to ascending. Sorts by version.

        limit : typing.Optional[int]
            Must be between 0 and 1000. No default.

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

        Returns
        -------
        HttpResponse[typing.List[Coverage]]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"coverages/v1/{jsonable_encoder(id)}/history",
            base_url=self._client_wrapper.get_environment().pre_encounter,
            method="GET",
            params={
                "start": str(start) if start is not None else None,
                "end": str(end) if end is not None else None,
                "non_auto_updated_coverages_only": non_auto_updated_coverages_only,
                "sort_direction": sort_direction,
                "limit": limit,
            },
            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(
                typing.List[Coverage],
                parse_obj_as(
                    type_=typing.List[Coverage],  # type: ignore
                    object_=_response_json,
                ),
            )
            return HttpResponse(response=_response, data=_data)
        if "errorName" in _response_json:
            if _response_json["errorName"] == "BadRequestError":
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorBase4Xx,
                        parse_obj_as(
                            type_=ErrorBase4Xx,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
            if _response_json["errorName"] == "NotFoundError":
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorBase4Xx,
                        parse_obj_as(
                            type_=ErrorBase4Xx,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def get_multi(
        self, *, patient_id: typing.Optional[str] = None, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[typing.List[Coverage]]:
        """
        Returns a list of Coverages based on the search criteria.

        Parameters
        ----------
        patient_id : typing.Optional[str]

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

        Returns
        -------
        HttpResponse[typing.List[Coverage]]
        """
        _response = self._client_wrapper.httpx_client.request(
            "coverages/v1",
            base_url=self._client_wrapper.get_environment().pre_encounter,
            method="GET",
            params={
                "patient_id": patient_id,
            },
            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(
                typing.List[Coverage],
                parse_obj_as(
                    type_=typing.List[Coverage],  # 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 scan(
        self, *, since: dt.datetime, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[typing.List[Coverage]]:
        """
        Scans up to 100 coverage updates. The since query parameter is inclusive, and the result list is ordered by updatedAt ascending.

        **Polling Pattern:**
        To continuously poll for updates without gaps:
        1. Make your initial request with a `since` timestamp (e.g., `since=2020-01-01T13:00:00.000Z`)
        2. The API returns up to 100 coverage records, sorted by `updated_at` ascending
        3. Find the `updated_at` value from the last record in the response
        4. Use that `updated_at` value as the `since` parameter in your next request
        5. Repeat steps 2-4 to ingest updates until you receive an empty list

        **Important Notes:**
        - The `since` parameter is inclusive, so you may receive the last record from the previous batch again (you can deduplicate by ID and version)
        - All coverage records include `updated_at`, `id`, `version`, `deactivated`, and `updating_user` fields for tracking changes
        - Timestamps have millisecond resolution for precise ordering

        Parameters
        ----------
        since : dt.datetime

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

        Returns
        -------
        HttpResponse[typing.List[Coverage]]
        """
        _response = self._client_wrapper.httpx_client.request(
            "coverages/v1/updates/scan",
            base_url=self._client_wrapper.get_environment().pre_encounter,
            method="GET",
            params={
                "since": serialize_datetime(since),
            },
            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(
                typing.List[Coverage],
                parse_obj_as(
                    type_=typing.List[Coverage],  # 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 batch_update_ppg(
        self,
        ppg_id: PayerPlanGroupId,
        *,
        request: PayerPlanGroupFields,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[None]:
        """
        Finds all coverages associated with the given ppg_id and updates the ppg_fields for each coverage.

        Parameters
        ----------
        ppg_id : PayerPlanGroupId

        request : PayerPlanGroupFields

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

        Returns
        -------
        HttpResponse[None]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"coverages/v1/batch-update-ppg/{jsonable_encoder(ppg_id)}",
            base_url=self._client_wrapper.get_environment().pre_encounter,
            method="POST",
            json=request,
            request_options=request_options,
            omit=OMIT,
        )
        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)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def check_eligibility(
        self,
        id: CoverageId,
        *,
        service_code: ServiceTypeCode,
        date_of_service: dt.date,
        npi: str,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[EligibilityCheckMetadata]:
        """
        Initiates an eligibility check. Returns the metadata of the check if successfully initiated.

        Parameters
        ----------
        id : CoverageId

        service_code : ServiceTypeCode

        date_of_service : dt.date

        npi : str

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

        Returns
        -------
        HttpResponse[EligibilityCheckMetadata]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"coverages/v1/{jsonable_encoder(id)}/eligibility",
            base_url=self._client_wrapper.get_environment().pre_encounter,
            method="POST",
            json={
                "service_code": service_code,
                "date_of_service": date_of_service,
                "npi": npi,
            },
            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(
                EligibilityCheckMetadata,
                parse_obj_as(
                    type_=EligibilityCheckMetadata,  # 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 get_eligibility(
        self, id: CoverageId, check_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[CoverageEligibilityCheckResponse]:
        """
        Gets the eligibility of a patient for a specific coverage if successful.

        Parameters
        ----------
        id : CoverageId

        check_id : str

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

        Returns
        -------
        HttpResponse[CoverageEligibilityCheckResponse]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"coverages/v1/{jsonable_encoder(id)}/eligibility/{jsonable_encoder(check_id)}",
            base_url=self._client_wrapper.get_environment().pre_encounter,
            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(
                CoverageEligibilityCheckResponse,
                parse_obj_as(
                    type_=CoverageEligibilityCheckResponse,  # 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)


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

    async def create(
        self, *, request: MutableCoverage, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[Coverage]:
        """
        Creates a new Coverage. A Coverage provides the high-level identifiers and descriptors of a specific insurance plan for a specific individual - typically the information you can find on an insurance card. Additionally a coverage will include detailed benefits information covered by the specific plan for the individual.

        Parameters
        ----------
        request : MutableCoverage

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

        Returns
        -------
        AsyncHttpResponse[Coverage]
        """
        _response = await self._client_wrapper.httpx_client.request(
            "coverages/v1",
            base_url=self._client_wrapper.get_environment().pre_encounter,
            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(
                Coverage,
                parse_obj_as(
                    type_=Coverage,  # 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 update(
        self,
        id: CoverageId,
        version: str,
        *,
        request: MutableCoverage,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[Coverage]:
        """
        Updates a Coverage. The path must contain the next version number to prevent race conditions. For example, if the current version of the coverage is n, you will need to send a request to this endpoint with `/{id}/n+1` to update the coverage. Updating historic versions is not supported.

        Parameters
        ----------
        id : CoverageId

        version : str

        request : MutableCoverage

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

        Returns
        -------
        AsyncHttpResponse[Coverage]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"coverages/v1/{jsonable_encoder(id)}/{jsonable_encoder(version)}",
            base_url=self._client_wrapper.get_environment().pre_encounter,
            method="PUT",
            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(
                Coverage,
                parse_obj_as(
                    type_=Coverage,  # type: ignore
                    object_=_response_json,
                ),
            )
            return AsyncHttpResponse(response=_response, data=_data)
        if "errorName" in _response_json:
            if _response_json["errorName"] == "NotFoundError":
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorBase4Xx,
                        parse_obj_as(
                            type_=ErrorBase4Xx,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
            if _response_json["errorName"] == "VersionConflictError":
                raise VersionConflictError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        VersionConflictErrorBody,
                        parse_obj_as(
                            type_=VersionConflictErrorBody,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def get_multi_paginated(
        self,
        *,
        patient_id: typing.Optional[str] = None,
        payer_plan_group_id: typing.Optional[str] = None,
        page_token: typing.Optional[PageToken] = None,
        limit: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[CoveragesPage]:
        """
        Returns a page of Coverages based on the search criteria.

        Parameters
        ----------
        patient_id : typing.Optional[str]

        payer_plan_group_id : typing.Optional[str]

        page_token : typing.Optional[PageToken]

        limit : typing.Optional[int]
            Must be between 0 and 1000. Defaults to 100

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

        Returns
        -------
        AsyncHttpResponse[CoveragesPage]
        """
        _response = await self._client_wrapper.httpx_client.request(
            "coverages/v1/get-multi-paginated",
            base_url=self._client_wrapper.get_environment().pre_encounter,
            method="GET",
            params={
                "patient_id": patient_id,
                "payer_plan_group_id": payer_plan_group_id,
                "page_token": page_token,
                "limit": limit,
            },
            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(
                CoveragesPage,
                parse_obj_as(
                    type_=CoveragesPage,  # type: ignore
                    object_=_response_json,
                ),
            )
            return AsyncHttpResponse(response=_response, data=_data)
        if "errorName" in _response_json:
            if _response_json["errorName"] == "BadRequestError":
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorBase4Xx,
                        parse_obj_as(
                            type_=ErrorBase4Xx,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def get(
        self, id: CoverageId, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[Coverage]:
        """
        gets a specific Coverage

        Parameters
        ----------
        id : CoverageId

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

        Returns
        -------
        AsyncHttpResponse[Coverage]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"coverages/v1/{jsonable_encoder(id)}",
            base_url=self._client_wrapper.get_environment().pre_encounter,
            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(
                Coverage,
                parse_obj_as(
                    type_=Coverage,  # 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 get_history(
        self,
        id: CoverageId,
        *,
        start: typing.Optional[dt.date] = None,
        end: typing.Optional[dt.date] = None,
        non_auto_updated_coverages_only: typing.Optional[bool] = None,
        sort_direction: typing.Optional[SortDirection] = None,
        limit: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[typing.List[Coverage]]:
        """
        Gets a coverage's history. Full history is returned if no filters are
        defined. The return list is ordered by version, defaulting to ascending.

        Parameters
        ----------
        id : CoverageId

        start : typing.Optional[dt.date]

        end : typing.Optional[dt.date]

        non_auto_updated_coverages_only : typing.Optional[bool]
            If true, only returns coverages that have NOT been auto-updated by the system.

        sort_direction : typing.Optional[SortDirection]
            Defaults to ascending. Sorts by version.

        limit : typing.Optional[int]
            Must be between 0 and 1000. No default.

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

        Returns
        -------
        AsyncHttpResponse[typing.List[Coverage]]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"coverages/v1/{jsonable_encoder(id)}/history",
            base_url=self._client_wrapper.get_environment().pre_encounter,
            method="GET",
            params={
                "start": str(start) if start is not None else None,
                "end": str(end) if end is not None else None,
                "non_auto_updated_coverages_only": non_auto_updated_coverages_only,
                "sort_direction": sort_direction,
                "limit": limit,
            },
            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(
                typing.List[Coverage],
                parse_obj_as(
                    type_=typing.List[Coverage],  # type: ignore
                    object_=_response_json,
                ),
            )
            return AsyncHttpResponse(response=_response, data=_data)
        if "errorName" in _response_json:
            if _response_json["errorName"] == "BadRequestError":
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorBase4Xx,
                        parse_obj_as(
                            type_=ErrorBase4Xx,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
            if _response_json["errorName"] == "NotFoundError":
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorBase4Xx,
                        parse_obj_as(
                            type_=ErrorBase4Xx,  # 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, *, patient_id: typing.Optional[str] = None, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[typing.List[Coverage]]:
        """
        Returns a list of Coverages based on the search criteria.

        Parameters
        ----------
        patient_id : typing.Optional[str]

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

        Returns
        -------
        AsyncHttpResponse[typing.List[Coverage]]
        """
        _response = await self._client_wrapper.httpx_client.request(
            "coverages/v1",
            base_url=self._client_wrapper.get_environment().pre_encounter,
            method="GET",
            params={
                "patient_id": patient_id,
            },
            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(
                typing.List[Coverage],
                parse_obj_as(
                    type_=typing.List[Coverage],  # 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 scan(
        self, *, since: dt.datetime, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[typing.List[Coverage]]:
        """
        Scans up to 100 coverage updates. The since query parameter is inclusive, and the result list is ordered by updatedAt ascending.

        **Polling Pattern:**
        To continuously poll for updates without gaps:
        1. Make your initial request with a `since` timestamp (e.g., `since=2020-01-01T13:00:00.000Z`)
        2. The API returns up to 100 coverage records, sorted by `updated_at` ascending
        3. Find the `updated_at` value from the last record in the response
        4. Use that `updated_at` value as the `since` parameter in your next request
        5. Repeat steps 2-4 to ingest updates until you receive an empty list

        **Important Notes:**
        - The `since` parameter is inclusive, so you may receive the last record from the previous batch again (you can deduplicate by ID and version)
        - All coverage records include `updated_at`, `id`, `version`, `deactivated`, and `updating_user` fields for tracking changes
        - Timestamps have millisecond resolution for precise ordering

        Parameters
        ----------
        since : dt.datetime

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

        Returns
        -------
        AsyncHttpResponse[typing.List[Coverage]]
        """
        _response = await self._client_wrapper.httpx_client.request(
            "coverages/v1/updates/scan",
            base_url=self._client_wrapper.get_environment().pre_encounter,
            method="GET",
            params={
                "since": serialize_datetime(since),
            },
            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(
                typing.List[Coverage],
                parse_obj_as(
                    type_=typing.List[Coverage],  # 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 batch_update_ppg(
        self,
        ppg_id: PayerPlanGroupId,
        *,
        request: PayerPlanGroupFields,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[None]:
        """
        Finds all coverages associated with the given ppg_id and updates the ppg_fields for each coverage.

        Parameters
        ----------
        ppg_id : PayerPlanGroupId

        request : PayerPlanGroupFields

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

        Returns
        -------
        AsyncHttpResponse[None]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"coverages/v1/batch-update-ppg/{jsonable_encoder(ppg_id)}",
            base_url=self._client_wrapper.get_environment().pre_encounter,
            method="POST",
            json=request,
            request_options=request_options,
            omit=OMIT,
        )
        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)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def check_eligibility(
        self,
        id: CoverageId,
        *,
        service_code: ServiceTypeCode,
        date_of_service: dt.date,
        npi: str,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[EligibilityCheckMetadata]:
        """
        Initiates an eligibility check. Returns the metadata of the check if successfully initiated.

        Parameters
        ----------
        id : CoverageId

        service_code : ServiceTypeCode

        date_of_service : dt.date

        npi : str

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

        Returns
        -------
        AsyncHttpResponse[EligibilityCheckMetadata]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"coverages/v1/{jsonable_encoder(id)}/eligibility",
            base_url=self._client_wrapper.get_environment().pre_encounter,
            method="POST",
            json={
                "service_code": service_code,
                "date_of_service": date_of_service,
                "npi": npi,
            },
            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(
                EligibilityCheckMetadata,
                parse_obj_as(
                    type_=EligibilityCheckMetadata,  # 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 get_eligibility(
        self, id: CoverageId, check_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[CoverageEligibilityCheckResponse]:
        """
        Gets the eligibility of a patient for a specific coverage if successful.

        Parameters
        ----------
        id : CoverageId

        check_id : str

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

        Returns
        -------
        AsyncHttpResponse[CoverageEligibilityCheckResponse]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"coverages/v1/{jsonable_encoder(id)}/eligibility/{jsonable_encoder(check_id)}",
            base_url=self._client_wrapper.get_environment().pre_encounter,
            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(
                CoverageEligibilityCheckResponse,
                parse_obj_as(
                    type_=CoverageEligibilityCheckResponse,  # 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)
