# 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.entity_not_found_error import EntityNotFoundError
from ....commons.errors.unauthorized_error import UnauthorizedError
from ....commons.types.claim_id import ClaimId
from ....commons.types.entity_not_found_error_message import EntityNotFoundErrorMessage
from ....commons.types.page_token import PageToken
from ....commons.types.unauthorized_error_message import UnauthorizedErrorMessage
from .errors.invalid_filters_error import InvalidFiltersError
from .types.invalid_filters_error_type import InvalidFiltersErrorType
from .types.invoice_itemization_response import InvoiceItemizationResponse
from .types.list_inventory_paged_response import ListInventoryPagedResponse


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

    def list_inventory(
        self,
        *,
        since: typing.Optional[dt.datetime] = None,
        limit: typing.Optional[int] = None,
        page_token: typing.Optional[PageToken] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ListInventoryPagedResponse]:
        """
        Retrieve a list of inventory records based on the provided filters. Each inventory record provides the latest invoiceable status of the associated claim.
        The response is paginated, and the `page_token` can be used to retrieve subsequent pages. Initial requests should not include `page_token`.

        Parameters
        ----------
        since : typing.Optional[dt.datetime]
            Timestamp to filter records since, inclusive

        limit : typing.Optional[int]
            Maximum number of records to return, default is 100

        page_token : typing.Optional[PageToken]

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

        Returns
        -------
        HttpResponse[ListInventoryPagedResponse]
        """
        _response = self._client_wrapper.httpx_client.request(
            "api/patient-ar/v1/inventory",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="GET",
            params={
                "since": serialize_datetime(since) if since is not None else None,
                "limit": limit,
                "page_token": page_token,
            },
            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(
                ListInventoryPagedResponse,
                parse_obj_as(
                    type_=ListInventoryPagedResponse,  # type: ignore
                    object_=_response_json,
                ),
            )
            return HttpResponse(response=_response, data=_data)
        if "errorName" in _response_json:
            if _response_json["errorName"] == "InvalidFiltersError":
                raise InvalidFiltersError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        InvalidFiltersErrorType,
                        parse_obj_as(
                            type_=InvalidFiltersErrorType,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
            if _response_json["errorName"] == "UnauthorizedError":
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        UnauthorizedErrorMessage,
                        parse_obj_as(
                            type_=UnauthorizedErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def itemize(
        self, claim_id: ClaimId, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[InvoiceItemizationResponse]:
        """
        Provides detailed itemization of invoice data for a specific claim.

        Parameters
        ----------
        claim_id : ClaimId

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

        Returns
        -------
        HttpResponse[InvoiceItemizationResponse]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/patient-ar/v1/invoice-itemization/{jsonable_encoder(claim_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(
                InvoiceItemizationResponse,
                parse_obj_as(
                    type_=InvoiceItemizationResponse,  # type: ignore
                    object_=_response_json,
                ),
            )
            return HttpResponse(response=_response, data=_data)
        if "errorName" in _response_json:
            if _response_json["errorName"] == "EntityNotFoundError":
                raise EntityNotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        EntityNotFoundErrorMessage,
                        parse_obj_as(
                            type_=EntityNotFoundErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
            if _response_json["errorName"] == "UnauthorizedError":
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        UnauthorizedErrorMessage,
                        parse_obj_as(
                            type_=UnauthorizedErrorMessage,  # 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 list_inventory(
        self,
        *,
        since: typing.Optional[dt.datetime] = None,
        limit: typing.Optional[int] = None,
        page_token: typing.Optional[PageToken] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ListInventoryPagedResponse]:
        """
        Retrieve a list of inventory records based on the provided filters. Each inventory record provides the latest invoiceable status of the associated claim.
        The response is paginated, and the `page_token` can be used to retrieve subsequent pages. Initial requests should not include `page_token`.

        Parameters
        ----------
        since : typing.Optional[dt.datetime]
            Timestamp to filter records since, inclusive

        limit : typing.Optional[int]
            Maximum number of records to return, default is 100

        page_token : typing.Optional[PageToken]

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

        Returns
        -------
        AsyncHttpResponse[ListInventoryPagedResponse]
        """
        _response = await self._client_wrapper.httpx_client.request(
            "api/patient-ar/v1/inventory",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="GET",
            params={
                "since": serialize_datetime(since) if since is not None else None,
                "limit": limit,
                "page_token": page_token,
            },
            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(
                ListInventoryPagedResponse,
                parse_obj_as(
                    type_=ListInventoryPagedResponse,  # type: ignore
                    object_=_response_json,
                ),
            )
            return AsyncHttpResponse(response=_response, data=_data)
        if "errorName" in _response_json:
            if _response_json["errorName"] == "InvalidFiltersError":
                raise InvalidFiltersError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        InvalidFiltersErrorType,
                        parse_obj_as(
                            type_=InvalidFiltersErrorType,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
            if _response_json["errorName"] == "UnauthorizedError":
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        UnauthorizedErrorMessage,
                        parse_obj_as(
                            type_=UnauthorizedErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def itemize(
        self, claim_id: ClaimId, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[InvoiceItemizationResponse]:
        """
        Provides detailed itemization of invoice data for a specific claim.

        Parameters
        ----------
        claim_id : ClaimId

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

        Returns
        -------
        AsyncHttpResponse[InvoiceItemizationResponse]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/patient-ar/v1/invoice-itemization/{jsonable_encoder(claim_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(
                InvoiceItemizationResponse,
                parse_obj_as(
                    type_=InvoiceItemizationResponse,  # type: ignore
                    object_=_response_json,
                ),
            )
            return AsyncHttpResponse(response=_response, data=_data)
        if "errorName" in _response_json:
            if _response_json["errorName"] == "EntityNotFoundError":
                raise EntityNotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        EntityNotFoundErrorMessage,
                        parse_obj_as(
                            type_=EntityNotFoundErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
            if _response_json["errorName"] == "UnauthorizedError":
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        UnauthorizedErrorMessage,
                        parse_obj_as(
                            type_=UnauthorizedErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
