# 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.jsonable_encoder import jsonable_encoder
from .....core.pydantic_utilities import pydantic_v1
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 V1Client:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._client_wrapper = client_wrapper

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

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

        from candid.client import CandidApiClient
        from candid.resources.import_invoice.v_1 import CreateImportInvoiceRequest
        from candid.resources.invoices.v_2 import (
            InvoiceItemAttributionCreate_ServiceLineId,
            InvoiceItemCreate,
            InvoiceStatus,
        )

        client = CandidApiClient(
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.import_invoice.v_1.import_invoice(
            request=CreateImportInvoiceRequest(
                external_payment_account_config_id=uuid.UUID(
                    "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32",
                ),
                patient_external_id="string",
                external_customer_identifier="string",
                note="string",
                due_date=datetime.date.fromisoformat(
                    "2023-01-15",
                ),
                items=[
                    InvoiceItemCreate(
                        attribution=InvoiceItemAttributionCreate_ServiceLineId(
                            value=uuid.UUID(
                                "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32",
                            )
                        ),
                        amount_cents=1,
                    )
                ],
                status=InvoiceStatus.DRAFT,
                external_identifier="string",
                customer_invoice_url="string",
            ),
        )
        """
        _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, body=_response.text)
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(ImportInvoice, _response_json)  # type: ignore
        if "errorName" in _response_json:
            if _response_json["errorName"] == "UnprocessableEntityError":
                raise UnprocessableEntityError(
                    pydantic_v1.parse_obj_as(UnprocessableEntityErrorMessage, _response_json["content"])  # type: ignore
                )
            if _response_json["errorName"] == "EntityConflictError":
                raise EntityConflictError(
                    pydantic_v1.parse_obj_as(EntityConflictErrorMessage, _response_json["content"])  # type: ignore
                )
        raise ApiError(status_code=_response.status_code, 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,
    ) -> 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
        -------
        ImportInvoicesPage

        Examples
        --------
        import datetime

        from candid import SortDirection
        from candid.client import CandidApiClient
        from candid.resources.invoices.v_2 import InvoiceSortField, InvoiceStatus

        client = CandidApiClient(
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.import_invoice.v_1.get_multi(
            patient_external_id="string",
            encounter_external_id="string",
            note="string",
            due_date_before=datetime.date.fromisoformat(
                "2023-01-15",
            ),
            due_date_after=datetime.date.fromisoformat(
                "2023-01-15",
            ),
            status=InvoiceStatus.DRAFT,
            limit=1,
            sort=InvoiceSortField.CREATED_AT,
            sort_direction=SortDirection.ASC,
            page_token="eyJ0b2tlbiI6IjEiLCJwYWdlX3Rva2VuIjoiMiJ9",
        )
        """
        _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, body=_response.text)
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(ImportInvoicesPage, _response_json)  # type: ignore
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def get(self, invoice_id: InvoiceId, *, request_options: typing.Optional[RequestOptions] = None) -> ImportInvoice:
        """
        Retrieve and view an import invoice

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

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

        Returns
        -------
        ImportInvoice

        Examples
        --------
        import uuid

        from candid.client import CandidApiClient

        client = CandidApiClient(
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.import_invoice.v_1.get(
            invoice_id=uuid.UUID(
                "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32",
            ),
        )
        """
        _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, body=_response.text)
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(ImportInvoice, _response_json)  # type: ignore
        if "errorName" in _response_json:
            if _response_json["errorName"] == "EntityNotFoundError":
                raise EntityNotFoundError(
                    pydantic_v1.parse_obj_as(EntityNotFoundErrorMessage, _response_json["content"])  # type: ignore
                )
        raise ApiError(status_code=_response.status_code, body=_response_json)

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

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

        request : ImportInvoiceUpdateRequest

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

        Returns
        -------
        ImportInvoice

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

        from candid.client import CandidApiClient
        from candid.resources.import_invoice.v_1 import (
            ImportInvoiceUpdateRequest,
            InvoiceItemInfoUpdate,
            InvoiceItemUpdateType,
        )
        from candid.resources.invoices.v_2 import (
            InvoiceItemAttributionCreate_ServiceLineId,
            InvoiceItemCreate,
            InvoiceStatus,
        )

        client = CandidApiClient(
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.import_invoice.v_1.update(
            invoice_id=uuid.UUID(
                "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32",
            ),
            request=ImportInvoiceUpdateRequest(
                customer_invoice_url="string",
                status=InvoiceStatus.DRAFT,
                note="string",
                due_date=datetime.date.fromisoformat(
                    "2023-01-15",
                ),
                items=InvoiceItemInfoUpdate(
                    update_type=InvoiceItemUpdateType.APPEND,
                    items=[
                        InvoiceItemCreate(
                            attribution=InvoiceItemAttributionCreate_ServiceLineId(
                                value=uuid.UUID(
                                    "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32",
                                )
                            ),
                            amount_cents=1,
                        )
                    ],
                ),
            ),
        )
        """
        _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, body=_response.text)
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(ImportInvoice, _response_json)  # type: ignore
        if "errorName" in _response_json:
            if _response_json["errorName"] == "EntityNotFoundError":
                raise EntityNotFoundError(
                    pydantic_v1.parse_obj_as(EntityNotFoundErrorMessage, _response_json["content"])  # 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 import_invoice(
        self, *, request: CreateImportInvoiceRequest, request_options: typing.Optional[RequestOptions] = None
    ) -> 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
        -------
        ImportInvoice

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

        from candid.client import AsyncCandidApiClient
        from candid.resources.import_invoice.v_1 import CreateImportInvoiceRequest
        from candid.resources.invoices.v_2 import (
            InvoiceItemAttributionCreate_ServiceLineId,
            InvoiceItemCreate,
            InvoiceStatus,
        )

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


        async def main() -> None:
            await client.import_invoice.v_1.import_invoice(
                request=CreateImportInvoiceRequest(
                    external_payment_account_config_id=uuid.UUID(
                        "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32",
                    ),
                    patient_external_id="string",
                    external_customer_identifier="string",
                    note="string",
                    due_date=datetime.date.fromisoformat(
                        "2023-01-15",
                    ),
                    items=[
                        InvoiceItemCreate(
                            attribution=InvoiceItemAttributionCreate_ServiceLineId(
                                value=uuid.UUID(
                                    "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32",
                                )
                            ),
                            amount_cents=1,
                        )
                    ],
                    status=InvoiceStatus.DRAFT,
                    external_identifier="string",
                    customer_invoice_url="string",
                ),
            )


        asyncio.run(main())
        """
        _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, body=_response.text)
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(ImportInvoice, _response_json)  # type: ignore
        if "errorName" in _response_json:
            if _response_json["errorName"] == "UnprocessableEntityError":
                raise UnprocessableEntityError(
                    pydantic_v1.parse_obj_as(UnprocessableEntityErrorMessage, _response_json["content"])  # type: ignore
                )
            if _response_json["errorName"] == "EntityConflictError":
                raise EntityConflictError(
                    pydantic_v1.parse_obj_as(EntityConflictErrorMessage, _response_json["content"])  # type: ignore
                )
        raise ApiError(status_code=_response.status_code, 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,
    ) -> 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
        -------
        ImportInvoicesPage

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

        from candid import SortDirection
        from candid.client import AsyncCandidApiClient
        from candid.resources.invoices.v_2 import InvoiceSortField, InvoiceStatus

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


        async def main() -> None:
            await client.import_invoice.v_1.get_multi(
                patient_external_id="string",
                encounter_external_id="string",
                note="string",
                due_date_before=datetime.date.fromisoformat(
                    "2023-01-15",
                ),
                due_date_after=datetime.date.fromisoformat(
                    "2023-01-15",
                ),
                status=InvoiceStatus.DRAFT,
                limit=1,
                sort=InvoiceSortField.CREATED_AT,
                sort_direction=SortDirection.ASC,
                page_token="eyJ0b2tlbiI6IjEiLCJwYWdlX3Rva2VuIjoiMiJ9",
            )


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

    async def get(
        self, invoice_id: InvoiceId, *, request_options: typing.Optional[RequestOptions] = None
    ) -> ImportInvoice:
        """
        Retrieve and view an import invoice

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

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

        Returns
        -------
        ImportInvoice

        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.import_invoice.v_1.get(
                invoice_id=uuid.UUID(
                    "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32",
                ),
            )


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

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

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

        request : ImportInvoiceUpdateRequest

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

        Returns
        -------
        ImportInvoice

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

        from candid.client import AsyncCandidApiClient
        from candid.resources.import_invoice.v_1 import (
            ImportInvoiceUpdateRequest,
            InvoiceItemInfoUpdate,
            InvoiceItemUpdateType,
        )
        from candid.resources.invoices.v_2 import (
            InvoiceItemAttributionCreate_ServiceLineId,
            InvoiceItemCreate,
            InvoiceStatus,
        )

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


        async def main() -> None:
            await client.import_invoice.v_1.update(
                invoice_id=uuid.UUID(
                    "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32",
                ),
                request=ImportInvoiceUpdateRequest(
                    customer_invoice_url="string",
                    status=InvoiceStatus.DRAFT,
                    note="string",
                    due_date=datetime.date.fromisoformat(
                        "2023-01-15",
                    ),
                    items=InvoiceItemInfoUpdate(
                        update_type=InvoiceItemUpdateType.APPEND,
                        items=[
                            InvoiceItemCreate(
                                attribution=InvoiceItemAttributionCreate_ServiceLineId(
                                    value=uuid.UUID(
                                        "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32",
                                    )
                                ),
                                amount_cents=1,
                            )
                        ],
                    ),
                ),
            )


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