# 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.jsonable_encoder import jsonable_encoder
from .......core.pydantic_utilities import pydantic_v1
from .......core.request_options import RequestOptions
from ....common.errors.not_found_error import NotFoundError
from ....common.errors.version_conflict_error import VersionConflictError
from ....common.types.not_found_error_body import NotFoundErrorBody
from ....common.types.version_conflict_error_body import VersionConflictErrorBody
from .types.coverage import Coverage
from .types.coverage_id import CoverageId
from .types.mutable_coverage import MutableCoverage

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


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

    def create(self, *, request: MutableCoverage, request_options: typing.Optional[RequestOptions] = None) -> 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
        -------
        Coverage

        Examples
        --------
        import datetime

        from candid.client import CandidApiClient
        from candid.resources.pre_encounter import HumanName, Period, Relationship, Sex
        from candid.resources.pre_encounter.coverages.v_1 import (
            CoverageStatus,
            InsurancePlan,
            InsuranceTypeCode,
            MutableCoverage,
            NetworkType,
            Subscriber,
        )

        client = CandidApiClient(
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.pre_encounter.coverages.v_1.create(
            request=MutableCoverage(
                status=CoverageStatus.ACTIVE,
                subscriber=Subscriber(
                    name=HumanName(),
                    date_of_birth=datetime.date.fromisoformat(
                        "2023-01-15",
                    ),
                    biological_sex=Sex.FEMALE,
                ),
                relationship=Relationship.SELF,
                patient="string",
                insurance_plan=InsurancePlan(
                    member_id="string",
                    payer_id="string",
                    payer_name="string",
                    group_number="string",
                    name="string",
                    plan_type=NetworkType.SELF_PAY,
                    type=InsuranceTypeCode.C_01,
                    period=Period(),
                    insurance_card_image_locator="string",
                ),
                verified=True,
            ),
        )
        """
        _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, body=_response.text)
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(Coverage, _response_json)  # type: ignore
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def update(
        self,
        id: CoverageId,
        version: str,
        *,
        request: MutableCoverage,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> Coverage:
        """
        Updates a Coverage. The path must contain the most recent version to prevent races. Updating historic versions is not supported.

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

        version : str

        request : MutableCoverage

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

        Returns
        -------
        Coverage

        Examples
        --------
        import datetime
        import uuid

        from candid.client import CandidApiClient
        from candid.resources.pre_encounter import HumanName, Period, Relationship, Sex
        from candid.resources.pre_encounter.coverages.v_1 import (
            CoverageStatus,
            InsurancePlan,
            InsuranceTypeCode,
            MutableCoverage,
            NetworkType,
            Subscriber,
        )

        client = CandidApiClient(
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.pre_encounter.coverages.v_1.update(
            id=uuid.UUID(
                "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32",
            ),
            version="string",
            request=MutableCoverage(
                status=CoverageStatus.ACTIVE,
                subscriber=Subscriber(
                    name=HumanName(),
                    date_of_birth=datetime.date.fromisoformat(
                        "2023-01-15",
                    ),
                    biological_sex=Sex.FEMALE,
                ),
                relationship=Relationship.SELF,
                patient="string",
                insurance_plan=InsurancePlan(
                    member_id="string",
                    payer_id="string",
                    payer_name="string",
                    group_number="string",
                    name="string",
                    plan_type=NetworkType.SELF_PAY,
                    type=InsuranceTypeCode.C_01,
                    period=Period(),
                    insurance_card_image_locator="string",
                ),
                verified=True,
            ),
        )
        """
        _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, body=_response.text)
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(Coverage, _response_json)  # type: ignore
        if "errorName" in _response_json:
            if _response_json["errorName"] == "NotFoundError":
                raise NotFoundError(
                    pydantic_v1.parse_obj_as(NotFoundErrorBody, _response_json["content"])  # type: ignore
                )
            if _response_json["errorName"] == "VersionConflictError":
                raise VersionConflictError(
                    pydantic_v1.parse_obj_as(VersionConflictErrorBody, _response_json["content"])  # type: ignore
                )
        raise ApiError(status_code=_response.status_code, body=_response_json)

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

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

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

        Returns
        -------
        Coverage

        Examples
        --------
        import uuid

        from candid.client import CandidApiClient

        client = CandidApiClient(
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.pre_encounter.coverages.v_1.get(
            id=uuid.UUID(
                "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32",
            ),
        )
        """
        _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, body=_response.text)
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(Coverage, _response_json)  # type: ignore
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def get_history(
        self, id: CoverageId, *, request_options: typing.Optional[RequestOptions] = None
    ) -> typing.List[Coverage]:
        """
        Gets a coverage along with it's full history. The return list is ordered by version ascending.

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

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

        Returns
        -------
        typing.List[Coverage]

        Examples
        --------
        import uuid

        from candid.client import CandidApiClient

        client = CandidApiClient(
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.pre_encounter.coverages.v_1.get_history(
            id=uuid.UUID(
                "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32",
            ),
        )
        """
        _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",
            request_options=request_options,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(typing.List[Coverage], _response_json)  # type: ignore
        if "errorName" in _response_json:
            if _response_json["errorName"] == "NotFoundError":
                raise NotFoundError(
                    pydantic_v1.parse_obj_as(NotFoundErrorBody, _response_json["content"])  # type: ignore
                )
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def get_multi(
        self, *, patient_id: typing.Optional[str] = None, request_options: typing.Optional[RequestOptions] = None
    ) -> 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
        -------
        typing.List[Coverage]

        Examples
        --------
        from candid.client import CandidApiClient

        client = CandidApiClient(
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.pre_encounter.coverages.v_1.get_multi(
            patient_id="string",
        )
        """
        _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, body=_response.text)
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(typing.List[Coverage], _response_json)  # type: ignore
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def scan(
        self, *, since: dt.datetime, request_options: typing.Optional[RequestOptions] = None
    ) -> typing.List[Coverage]:
        """
        Scans up to 100 coverage updates. The since query parameter is inclusive, and the result list is ordered by updatedAt descending.

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

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

        Returns
        -------
        typing.List[Coverage]

        Examples
        --------
        import datetime

        from candid.client import CandidApiClient

        client = CandidApiClient(
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.pre_encounter.coverages.v_1.scan(
            since=datetime.datetime.fromisoformat(
                "2024-01-15 09:30:00+00:00",
            ),
        )
        """
        _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, body=_response.text)
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(typing.List[Coverage], _response_json)  # type: ignore
        raise ApiError(status_code=_response.status_code, body=_response_json)


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

    async def create(
        self, *, request: MutableCoverage, request_options: typing.Optional[RequestOptions] = None
    ) -> 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
        -------
        Coverage

        Examples
        --------
        import asyncio
        import datetime

        from candid.client import AsyncCandidApiClient
        from candid.resources.pre_encounter import HumanName, Period, Relationship, Sex
        from candid.resources.pre_encounter.coverages.v_1 import (
            CoverageStatus,
            InsurancePlan,
            InsuranceTypeCode,
            MutableCoverage,
            NetworkType,
            Subscriber,
        )

        client = AsyncCandidApiClient(
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )


        async def main() -> None:
            await client.pre_encounter.coverages.v_1.create(
                request=MutableCoverage(
                    status=CoverageStatus.ACTIVE,
                    subscriber=Subscriber(
                        name=HumanName(),
                        date_of_birth=datetime.date.fromisoformat(
                            "2023-01-15",
                        ),
                        biological_sex=Sex.FEMALE,
                    ),
                    relationship=Relationship.SELF,
                    patient="string",
                    insurance_plan=InsurancePlan(
                        member_id="string",
                        payer_id="string",
                        payer_name="string",
                        group_number="string",
                        name="string",
                        plan_type=NetworkType.SELF_PAY,
                        type=InsuranceTypeCode.C_01,
                        period=Period(),
                        insurance_card_image_locator="string",
                    ),
                    verified=True,
                ),
            )


        asyncio.run(main())
        """
        _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, body=_response.text)
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(Coverage, _response_json)  # type: ignore
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def update(
        self,
        id: CoverageId,
        version: str,
        *,
        request: MutableCoverage,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> Coverage:
        """
        Updates a Coverage. The path must contain the most recent version to prevent races. Updating historic versions is not supported.

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

        version : str

        request : MutableCoverage

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

        Returns
        -------
        Coverage

        Examples
        --------
        import asyncio
        import datetime
        import uuid

        from candid.client import AsyncCandidApiClient
        from candid.resources.pre_encounter import HumanName, Period, Relationship, Sex
        from candid.resources.pre_encounter.coverages.v_1 import (
            CoverageStatus,
            InsurancePlan,
            InsuranceTypeCode,
            MutableCoverage,
            NetworkType,
            Subscriber,
        )

        client = AsyncCandidApiClient(
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )


        async def main() -> None:
            await client.pre_encounter.coverages.v_1.update(
                id=uuid.UUID(
                    "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32",
                ),
                version="string",
                request=MutableCoverage(
                    status=CoverageStatus.ACTIVE,
                    subscriber=Subscriber(
                        name=HumanName(),
                        date_of_birth=datetime.date.fromisoformat(
                            "2023-01-15",
                        ),
                        biological_sex=Sex.FEMALE,
                    ),
                    relationship=Relationship.SELF,
                    patient="string",
                    insurance_plan=InsurancePlan(
                        member_id="string",
                        payer_id="string",
                        payer_name="string",
                        group_number="string",
                        name="string",
                        plan_type=NetworkType.SELF_PAY,
                        type=InsuranceTypeCode.C_01,
                        period=Period(),
                        insurance_card_image_locator="string",
                    ),
                    verified=True,
                ),
            )


        asyncio.run(main())
        """
        _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, body=_response.text)
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(Coverage, _response_json)  # type: ignore
        if "errorName" in _response_json:
            if _response_json["errorName"] == "NotFoundError":
                raise NotFoundError(
                    pydantic_v1.parse_obj_as(NotFoundErrorBody, _response_json["content"])  # type: ignore
                )
            if _response_json["errorName"] == "VersionConflictError":
                raise VersionConflictError(
                    pydantic_v1.parse_obj_as(VersionConflictErrorBody, _response_json["content"])  # type: ignore
                )
        raise ApiError(status_code=_response.status_code, body=_response_json)

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

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

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

        Returns
        -------
        Coverage

        Examples
        --------
        import asyncio
        import uuid

        from candid.client import AsyncCandidApiClient

        client = AsyncCandidApiClient(
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )


        async def main() -> None:
            await client.pre_encounter.coverages.v_1.get(
                id=uuid.UUID(
                    "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32",
                ),
            )


        asyncio.run(main())
        """
        _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, body=_response.text)
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(Coverage, _response_json)  # type: ignore
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def get_history(
        self, id: CoverageId, *, request_options: typing.Optional[RequestOptions] = None
    ) -> typing.List[Coverage]:
        """
        Gets a coverage along with it's full history. The return list is ordered by version ascending.

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

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

        Returns
        -------
        typing.List[Coverage]

        Examples
        --------
        import asyncio
        import uuid

        from candid.client import AsyncCandidApiClient

        client = AsyncCandidApiClient(
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )


        async def main() -> None:
            await client.pre_encounter.coverages.v_1.get_history(
                id=uuid.UUID(
                    "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32",
                ),
            )


        asyncio.run(main())
        """
        _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",
            request_options=request_options,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(typing.List[Coverage], _response_json)  # type: ignore
        if "errorName" in _response_json:
            if _response_json["errorName"] == "NotFoundError":
                raise NotFoundError(
                    pydantic_v1.parse_obj_as(NotFoundErrorBody, _response_json["content"])  # type: ignore
                )
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def get_multi(
        self, *, patient_id: typing.Optional[str] = None, request_options: typing.Optional[RequestOptions] = None
    ) -> 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
        -------
        typing.List[Coverage]

        Examples
        --------
        import asyncio

        from candid.client import AsyncCandidApiClient

        client = AsyncCandidApiClient(
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )


        async def main() -> None:
            await client.pre_encounter.coverages.v_1.get_multi(
                patient_id="string",
            )


        asyncio.run(main())
        """
        _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, body=_response.text)
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(typing.List[Coverage], _response_json)  # type: ignore
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def scan(
        self, *, since: dt.datetime, request_options: typing.Optional[RequestOptions] = None
    ) -> typing.List[Coverage]:
        """
        Scans up to 100 coverage updates. The since query parameter is inclusive, and the result list is ordered by updatedAt descending.

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

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

        Returns
        -------
        typing.List[Coverage]

        Examples
        --------
        import asyncio
        import datetime

        from candid.client import AsyncCandidApiClient

        client = AsyncCandidApiClient(
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )


        async def main() -> None:
            await client.pre_encounter.coverages.v_1.scan(
                since=datetime.datetime.fromisoformat(
                    "2024-01-15 09:30:00+00:00",
                ),
            )


        asyncio.run(main())
        """
        _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, body=_response.text)
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(typing.List[Coverage], _response_json)  # type: ignore
        raise ApiError(status_code=_response.status_code, body=_response_json)
