# This file was auto-generated by Fern from our API Definition.

import urllib.parse
from json.decoder import JSONDecodeError

import httpx
import pydantic

from ...core.api_error import ApiError
from ...core.jsonable_encoder import jsonable_encoder
from ...core.remove_none_from_headers import remove_none_from_headers
from ...environment import CandidApiEnvironment
from ..commons.types.encounter_id import EncounterId
from .types.billing_note import BillingNote


class BillingNotesClient:
    def __init__(self, *, environment: CandidApiEnvironment = CandidApiEnvironment.PRODUCTION, token: str):
        self._environment = environment
        self._token = token

    def create(self, *, encounter_id: EncounterId, text: str) -> BillingNote:
        _response = httpx.request(
            "POST",
            urllib.parse.urljoin(f"{self._environment.value}/", "api/billing_notes/v2"),
            json=jsonable_encoder({"encounter_id": encounter_id, "text": text}),
            headers=remove_none_from_headers(
                {"Authorization": f"Bearer {self._token}" if self._token is not None else None}
            ),
            timeout=60,
        )
        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.parse_obj_as(BillingNote, _response_json)  # type: ignore
        raise ApiError(status_code=_response.status_code, body=_response_json)


class AsyncBillingNotesClient:
    def __init__(self, *, environment: CandidApiEnvironment = CandidApiEnvironment.PRODUCTION, token: str):
        self._environment = environment
        self._token = token

    async def create(self, *, encounter_id: EncounterId, text: str) -> BillingNote:
        async with httpx.AsyncClient() as _client:
            _response = await _client.request(
                "POST",
                urllib.parse.urljoin(f"{self._environment.value}/", "api/billing_notes/v2"),
                json=jsonable_encoder({"encounter_id": encounter_id, "text": text}),
                headers=remove_none_from_headers(
                    {"Authorization": f"Bearer {self._token}" if self._token is not None else None}
                ),
                timeout=60,
            )
        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.parse_obj_as(BillingNote, _response_json)  # type: ignore
        raise ApiError(status_code=_response.status_code, body=_response_json)
