from typing import Any, Dict, Optional
import httpx
from ..exceptions import AuthenticationError, DocufastError, NotFoundError, PermissionError

class BaseResource:
    def __init__(self, client: httpx.Client):
        self._client = client

    def _request(
        self,
        method: str,
        path: str,
        json: Optional[dict] = None,
        data: Optional[dict] = None,
        files: Optional[dict] = None,
        params: Optional[dict] = None,
    ) -> dict:
        kwargs = {"params": params}
        if files:
            kwargs["files"] = files
            if data:
                kwargs["data"] = data
        elif json is not None:
            kwargs["json"] = json

        response = self._client.request(method, path, **kwargs)

        if response.status_code == 401:
            raise AuthenticationError("Invalid API key", status_code=401)
        if response.status_code == 403:
            body = response.json() if response.content else {}
            raise PermissionError(
                body.get("ui_message", "Permission denied"), status_code=403
            )
        if response.status_code == 404:
            body = response.json() if response.content else {}
            raise NotFoundError(
                body.get("ui_message", "Not found"), status_code=404
            )
        if response.status_code >= 400:
            body = response.json() if response.content else {}
            raise DocufastError(
                body.get("ui_message", f"Request failed with status {response.status_code}"),
                status_code=response.status_code,
                response=body,
            )

        body = response.json()
        return body.get("data", body)
