import httpx

from ..errors import RequestError


class HttpClient:
    def __init__(
        self,
        api_key: str,
        base_url: str,
    ):
        self._async_http_client = httpx.AsyncClient(
            base_url=base_url,
            headers={
                "Authorization": f"Bearer {api_key}",
                "Content-Type": "application/json",
            },
        )

    async def get(self, path: str):
        response = await self._async_http_client.get(path)

        if response.status_code >= 400:
            try:
                error_detail = response.json()
                error_msg = error_detail.get("message", response.text)
                error_code = error_detail.get("error", response.status_code)
            except Exception:
                error_msg = response.text
                error_code = response.status_code

            raise RequestError(
                message=error_msg,
                status_code=response.status_code,
                context=f"path={path}, method=GET",
            )

        return response.json()

    async def post(self, path: str, json: dict):
        response = await self._async_http_client.post(path, json=json)

        if response.status_code >= 400:
            try:
                error_detail = response.json()
                error_msg = error_detail.get("message", response.text)
                error_code = error_detail.get("error", response.status_code)
            except Exception:
                error_msg = response.text
                error_code = response.status_code

            raise RequestError(
                message=error_msg,
                status_code=response.status_code,
                context=f"path={path}, method=POST",
            )

        return response.json()

    async def close(self):
        await self._async_http_client.close()
