from typing import Any
from typing import Protocol

import requests

from ssb_pubmd.common.exceptions import CmsClientError


class HttpClient(Protocol):
    def post(
        self, url: str, headers: dict[str, str], payload: dict[str, Any]
    ) -> dict[str, str]: ...


class RequestsHttpClient:
    def post(
        self, url: str, headers: dict[str, str], payload: dict[str, Any]
    ) -> dict[str, str]:
        try:
            response = requests.post(
                url,
                headers=headers,
                json=payload,
            )
            body = response.json()
        except Exception as err:
            raise CmsClientError(
                f"Sync failed. Could not parse response. Payload sent to {url}:\n{payload}"
            ) from err
        if not response.ok:
            raise CmsClientError(
                f"Sync failed. Payload sent to {url}:\n{payload}\nResponse message: {body.get('msg', 'no message')}"
            )
        return body  # type: ignore
