# 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.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_conflict_error import EntityConflictError
from ....commons.errors.entity_not_found_error import EntityNotFoundError
from ....commons.errors.unprocessable_entity_error import UnprocessableEntityError
from ....commons.types.encounter_external_id import EncounterExternalId
from ....commons.types.entity_conflict_error_message import EntityConflictErrorMessage
from ....commons.types.entity_not_found_error_message import EntityNotFoundErrorMessage
from ....commons.types.invoice_id import InvoiceId
from ....commons.types.page_token import PageToken
from ....commons.types.patient_external_id import PatientExternalId
from ....commons.types.sort_direction import SortDirection
from ....commons.types.unprocessable_entity_error_message import UnprocessableEntityErrorMessage
from ....invoices.resources.v_2.types.invoice_sort_field import InvoiceSortField
from ....invoices.resources.v_2.types.invoice_status import InvoiceStatus
from .types.create_import_invoice_request import CreateImportInvoiceRequest
from .types.import_invoice import ImportInvoice
from .types.import_invoice_update_request import ImportInvoiceUpdateRequest
from .types.import_invoices_page import ImportInvoicesPage

# 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 import_invoice(
        self, *, request: CreateImportInvoiceRequest, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[ImportInvoice]:
        """
        Import an existing invoice from a third party service to reflect state in Candid.

        Parameters
        ----------
        request : CreateImportInvoiceRequest

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

        Returns
        -------
        HttpResponse[ImportInvoice]
        """
        _response = self._client_wrapper.httpx_client.request(
            "api/import-invoice/v1",
            base_url=self._client_wrapper.get_environment().candid_api,
            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(
                ImportInvoice,
                parse_obj_as(
                    type_=ImportInvoice,  # type: ignore
                    object_=_response_json,
                ),
            )
            return HttpResponse(response=_response, data=_data)
        if "errorName" in _response_json:
            if _response_json["errorName"] == "UnprocessableEntityError":
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        UnprocessableEntityErrorMessage,
                        parse_obj_as(
                            type_=UnprocessableEntityErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
            if _response_json["errorName"] == "EntityConflictError":
                raise EntityConflictError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        EntityConflictErrorMessage,
                        parse_obj_as(
                            type_=EntityConflictErrorMessage,  # 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_external_id: typing.Optional[PatientExternalId] = None,
        encounter_external_id: typing.Optional[EncounterExternalId] = None,
        note: typing.Optional[str] = None,
        due_date_before: typing.Optional[dt.date] = None,
        due_date_after: typing.Optional[dt.date] = None,
        status: typing.Optional[typing.Union[InvoiceStatus, typing.Sequence[InvoiceStatus]]] = None,
        limit: typing.Optional[int] = None,
        sort: typing.Optional[InvoiceSortField] = None,
        sort_direction: typing.Optional[SortDirection] = None,
        page_token: typing.Optional[PageToken] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ImportInvoicesPage]:
        """
        Returns all Invoices for the authenticated user's organziation with all filters applied.

        Parameters
        ----------
        patient_external_id : typing.Optional[PatientExternalId]

        encounter_external_id : typing.Optional[EncounterExternalId]

        note : typing.Optional[str]
            partial match supported

        due_date_before : typing.Optional[dt.date]
            all invoices whose due date is before this due date, not inclusive

        due_date_after : typing.Optional[dt.date]
            all invoices whose due date is after this due date, not inclusive

        status : typing.Optional[typing.Union[InvoiceStatus, typing.Sequence[InvoiceStatus]]]
            all invoices that match any of the provided statuses

        limit : typing.Optional[int]
            Defaults to 100

        sort : typing.Optional[InvoiceSortField]
            Defaults to created_at

        sort_direction : typing.Optional[SortDirection]
            Sort direction. Defaults to descending order

        page_token : typing.Optional[PageToken]

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

        Returns
        -------
        HttpResponse[ImportInvoicesPage]
        """
        _response = self._client_wrapper.httpx_client.request(
            "api/import-invoice/v1",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="GET",
            params={
                "patient_external_id": patient_external_id,
                "encounter_external_id": encounter_external_id,
                "note": note,
                "due_date_before": str(due_date_before) if due_date_before is not None else None,
                "due_date_after": str(due_date_after) if due_date_after is not None else None,
                "status": status,
                "limit": limit,
                "sort": sort,
                "sort_direction": sort_direction,
                "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(
                ImportInvoicesPage,
                parse_obj_as(
                    type_=ImportInvoicesPage,  # 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(
        self, invoice_id: InvoiceId, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[ImportInvoice]:
        """
        Retrieve and view an import invoice

        Parameters
        ----------
        invoice_id : InvoiceId
            InvoiceId to be returned

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

        Returns
        -------
        HttpResponse[ImportInvoice]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/import-invoice/v1/{jsonable_encoder(invoice_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(
                ImportInvoice,
                parse_obj_as(
                    type_=ImportInvoice,  # 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"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def update(
        self,
        invoice_id: InvoiceId,
        *,
        request: ImportInvoiceUpdateRequest,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ImportInvoice]:
        """
        Update the information on the imported invoice

        Parameters
        ----------
        invoice_id : InvoiceId

        request : ImportInvoiceUpdateRequest

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

        Returns
        -------
        HttpResponse[ImportInvoice]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/import-invoice/v1/{jsonable_encoder(invoice_id)}",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="PATCH",
            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(
                ImportInvoice,
                parse_obj_as(
                    type_=ImportInvoice,  # 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"],
                        ),
                    ),
                )
        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 import_invoice(
        self, *, request: CreateImportInvoiceRequest, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[ImportInvoice]:
        """
        Import an existing invoice from a third party service to reflect state in Candid.

        Parameters
        ----------
        request : CreateImportInvoiceRequest

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

        Returns
        -------
        AsyncHttpResponse[ImportInvoice]
        """
        _response = await self._client_wrapper.httpx_client.request(
            "api/import-invoice/v1",
            base_url=self._client_wrapper.get_environment().candid_api,
            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(
                ImportInvoice,
                parse_obj_as(
                    type_=ImportInvoice,  # type: ignore
                    object_=_response_json,
                ),
            )
            return AsyncHttpResponse(response=_response, data=_data)
        if "errorName" in _response_json:
            if _response_json["errorName"] == "UnprocessableEntityError":
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        UnprocessableEntityErrorMessage,
                        parse_obj_as(
                            type_=UnprocessableEntityErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
            if _response_json["errorName"] == "EntityConflictError":
                raise EntityConflictError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        EntityConflictErrorMessage,
                        parse_obj_as(
                            type_=EntityConflictErrorMessage,  # 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_external_id: typing.Optional[PatientExternalId] = None,
        encounter_external_id: typing.Optional[EncounterExternalId] = None,
        note: typing.Optional[str] = None,
        due_date_before: typing.Optional[dt.date] = None,
        due_date_after: typing.Optional[dt.date] = None,
        status: typing.Optional[typing.Union[InvoiceStatus, typing.Sequence[InvoiceStatus]]] = None,
        limit: typing.Optional[int] = None,
        sort: typing.Optional[InvoiceSortField] = None,
        sort_direction: typing.Optional[SortDirection] = None,
        page_token: typing.Optional[PageToken] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ImportInvoicesPage]:
        """
        Returns all Invoices for the authenticated user's organziation with all filters applied.

        Parameters
        ----------
        patient_external_id : typing.Optional[PatientExternalId]

        encounter_external_id : typing.Optional[EncounterExternalId]

        note : typing.Optional[str]
            partial match supported

        due_date_before : typing.Optional[dt.date]
            all invoices whose due date is before this due date, not inclusive

        due_date_after : typing.Optional[dt.date]
            all invoices whose due date is after this due date, not inclusive

        status : typing.Optional[typing.Union[InvoiceStatus, typing.Sequence[InvoiceStatus]]]
            all invoices that match any of the provided statuses

        limit : typing.Optional[int]
            Defaults to 100

        sort : typing.Optional[InvoiceSortField]
            Defaults to created_at

        sort_direction : typing.Optional[SortDirection]
            Sort direction. Defaults to descending order

        page_token : typing.Optional[PageToken]

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

        Returns
        -------
        AsyncHttpResponse[ImportInvoicesPage]
        """
        _response = await self._client_wrapper.httpx_client.request(
            "api/import-invoice/v1",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="GET",
            params={
                "patient_external_id": patient_external_id,
                "encounter_external_id": encounter_external_id,
                "note": note,
                "due_date_before": str(due_date_before) if due_date_before is not None else None,
                "due_date_after": str(due_date_after) if due_date_after is not None else None,
                "status": status,
                "limit": limit,
                "sort": sort,
                "sort_direction": sort_direction,
                "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(
                ImportInvoicesPage,
                parse_obj_as(
                    type_=ImportInvoicesPage,  # 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(
        self, invoice_id: InvoiceId, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[ImportInvoice]:
        """
        Retrieve and view an import invoice

        Parameters
        ----------
        invoice_id : InvoiceId
            InvoiceId to be returned

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

        Returns
        -------
        AsyncHttpResponse[ImportInvoice]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/import-invoice/v1/{jsonable_encoder(invoice_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(
                ImportInvoice,
                parse_obj_as(
                    type_=ImportInvoice,  # 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"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def update(
        self,
        invoice_id: InvoiceId,
        *,
        request: ImportInvoiceUpdateRequest,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ImportInvoice]:
        """
        Update the information on the imported invoice

        Parameters
        ----------
        invoice_id : InvoiceId

        request : ImportInvoiceUpdateRequest

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

        Returns
        -------
        AsyncHttpResponse[ImportInvoice]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/import-invoice/v1/{jsonable_encoder(invoice_id)}",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="PATCH",
            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(
                ImportInvoice,
                parse_obj_as(
                    type_=ImportInvoice,  # 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"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
