# 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 ....commons.errors.bad_request_error import BadRequestError
from ....commons.errors.entity_not_found_error import EntityNotFoundError
from ....commons.errors.internal_error import InternalError
from ....commons.types.bad_request_error_message import BadRequestErrorMessage
from ....commons.types.entity_not_found_error_message import EntityNotFoundErrorMessage
from ....commons.types.internal_error_message import InternalErrorMessage
from ....commons.types.page_token import PageToken
from .types.event import Event
from .types.event_id import EventId
from .types.event_scan_page import EventScanPage


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

    def scan(
        self,
        *,
        page_token: typing.Optional[PageToken] = None,
        limit: typing.Optional[int] = None,
        event_types: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        created_before: typing.Optional[dt.datetime] = None,
        created_after: typing.Optional[dt.datetime] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[EventScanPage]:
        """
        Scans the last 30 days of events. All results are sorted by created date, descending.

        Parameters
        ----------
        page_token : typing.Optional[PageToken]

        limit : typing.Optional[int]
            Number of events to return. Minimum value is 1, maximum is 100. Defaults to 10.

        event_types : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Event types to filter on. Defaults to showing all event types.

            | Event Type | Description |
            |------------|-------------|
            | `CandidApi.Encounter.Created` | When a new claim is created |
            | `CandidApi.Encounter.StatusUpdated` | When a claim's status has been updated |
            | `PreEncounter.Patient.Created` | When a new patient has been created |
            | `PreEncounter.Patient.Updated` | When a patient's information has been updated |
            | `PreEncounter.Coverage.Created` | When a new coverage has been created for a patient |
            | `PreEncounter.Coverage.Updated` | When a patient's coverage has been updated |
            | `PreEncounter.Tag.Created` | When a new tag has been created for a patient |
            | `PreEncounter.Tag.Updated` | When a patient's tag has been updated |

        created_before : typing.Optional[dt.datetime]
            Filters for only events created before this time (inclusive).

        created_after : typing.Optional[dt.datetime]
            Filters for only events created after this time (inclusive).

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

        Returns
        -------
        HttpResponse[EventScanPage]
        """
        _response = self._client_wrapper.httpx_client.request(
            "api/events/v1/",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="GET",
            params={
                "page_token": page_token,
                "limit": limit,
                "event_types": event_types,
                "created_before": serialize_datetime(created_before) if created_before is not None else None,
                "created_after": serialize_datetime(created_after) if created_after is not None else None,
            },
            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(
                EventScanPage,
                parse_obj_as(
                    type_=EventScanPage,  # 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(
                        BadRequestErrorMessage,
                        parse_obj_as(
                            type_=BadRequestErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
            if _response_json["errorName"] == "InternalError":
                raise InternalError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        InternalErrorMessage,
                        parse_obj_as(
                            type_=InternalErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def get(self, event_id: EventId, *, request_options: typing.Optional[RequestOptions] = None) -> HttpResponse[Event]:
        """
        Parameters
        ----------
        event_id : EventId

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

        Returns
        -------
        HttpResponse[Event]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/events/v1/{jsonable_encoder(event_id)}",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="GET",
            request_options=request_options,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        if 200 <= _response.status_code < 300:
            _data = typing.cast(
                Event,
                parse_obj_as(
                    type_=Event,  # 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(
                        BadRequestErrorMessage,
                        parse_obj_as(
                            type_=BadRequestErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
            if _response_json["errorName"] == "InternalError":
                raise InternalError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        InternalErrorMessage,
                        parse_obj_as(
                            type_=InternalErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
            if _response_json["errorName"] == "EntityNotFoundError":
                raise EntityNotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        EntityNotFoundErrorMessage,
                        parse_obj_as(
                            type_=EntityNotFoundErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)


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

    async def scan(
        self,
        *,
        page_token: typing.Optional[PageToken] = None,
        limit: typing.Optional[int] = None,
        event_types: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        created_before: typing.Optional[dt.datetime] = None,
        created_after: typing.Optional[dt.datetime] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[EventScanPage]:
        """
        Scans the last 30 days of events. All results are sorted by created date, descending.

        Parameters
        ----------
        page_token : typing.Optional[PageToken]

        limit : typing.Optional[int]
            Number of events to return. Minimum value is 1, maximum is 100. Defaults to 10.

        event_types : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Event types to filter on. Defaults to showing all event types.

            | Event Type | Description |
            |------------|-------------|
            | `CandidApi.Encounter.Created` | When a new claim is created |
            | `CandidApi.Encounter.StatusUpdated` | When a claim's status has been updated |
            | `PreEncounter.Patient.Created` | When a new patient has been created |
            | `PreEncounter.Patient.Updated` | When a patient's information has been updated |
            | `PreEncounter.Coverage.Created` | When a new coverage has been created for a patient |
            | `PreEncounter.Coverage.Updated` | When a patient's coverage has been updated |
            | `PreEncounter.Tag.Created` | When a new tag has been created for a patient |
            | `PreEncounter.Tag.Updated` | When a patient's tag has been updated |

        created_before : typing.Optional[dt.datetime]
            Filters for only events created before this time (inclusive).

        created_after : typing.Optional[dt.datetime]
            Filters for only events created after this time (inclusive).

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

        Returns
        -------
        AsyncHttpResponse[EventScanPage]
        """
        _response = await self._client_wrapper.httpx_client.request(
            "api/events/v1/",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="GET",
            params={
                "page_token": page_token,
                "limit": limit,
                "event_types": event_types,
                "created_before": serialize_datetime(created_before) if created_before is not None else None,
                "created_after": serialize_datetime(created_after) if created_after is not None else None,
            },
            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(
                EventScanPage,
                parse_obj_as(
                    type_=EventScanPage,  # 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(
                        BadRequestErrorMessage,
                        parse_obj_as(
                            type_=BadRequestErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
            if _response_json["errorName"] == "InternalError":
                raise InternalError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        InternalErrorMessage,
                        parse_obj_as(
                            type_=InternalErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def get(
        self, event_id: EventId, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[Event]:
        """
        Parameters
        ----------
        event_id : EventId

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

        Returns
        -------
        AsyncHttpResponse[Event]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/events/v1/{jsonable_encoder(event_id)}",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="GET",
            request_options=request_options,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        if 200 <= _response.status_code < 300:
            _data = typing.cast(
                Event,
                parse_obj_as(
                    type_=Event,  # 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(
                        BadRequestErrorMessage,
                        parse_obj_as(
                            type_=BadRequestErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
            if _response_json["errorName"] == "InternalError":
                raise InternalError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        InternalErrorMessage,
                        parse_obj_as(
                            type_=InternalErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
            if _response_json["errorName"] == "EntityNotFoundError":
                raise EntityNotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        EntityNotFoundErrorMessage,
                        parse_obj_as(
                            type_=EntityNotFoundErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
