"""HTTP client for making API requests."""

import requests
from typing import Any, Dict, Optional
from .errors import LipanaError


class HttpClient:
    """HTTP client for Lipana API requests."""

    def __init__(self, api_key: str, base_url: str, environment: str):
        self.api_key = api_key
        self.base_url = base_url
        self.environment = environment
        self.session = requests.Session()
        self.session.headers.update({
            "Content-Type": "application/json",
            "User-Agent": "Lipana-Python-SDK/1.0.0",
            "x-api-key": api_key,
        })

    def _handle_response(self, response: requests.Response) -> Any:
        """Handle API response and raise errors if needed."""
        try:
            data = response.json()
        except ValueError:
            data = {}

        if not response.ok:
            message = data.get("message", response.reason or "An error occurred")
            code = data.get("code")
            errors = data.get("errors", {})
            raise LipanaError(message, response.status_code, code, errors)

        return data.get("data", data)

    def get(self, path: str, params: Optional[Dict] = None) -> Any:
        """Make a GET request."""
        url = f"{self.base_url}{path}"
        response = self.session.get(url, params=params, timeout=30)
        return self._handle_response(response)

    def post(self, path: str, data: Optional[Dict] = None) -> Any:
        """Make a POST request."""
        url = f"{self.base_url}{path}"
        response = self.session.post(url, json=data, timeout=30)
        return self._handle_response(response)

    def put(self, path: str, data: Optional[Dict] = None) -> Any:
        """Make a PUT request."""
        url = f"{self.base_url}{path}"
        response = self.session.put(url, json=data, timeout=30)
        return self._handle_response(response)

    def delete(self, path: str) -> Any:
        """Make a DELETE request."""
        url = f"{self.base_url}{path}"
        response = self.session.delete(url, timeout=30)
        return self._handle_response(response)

