from __future__ import annotations

from dataclasses import asdict
from typing import Any, Dict, Optional, TYPE_CHECKING

from ..types import ListAuditParams

if TYPE_CHECKING:
    from ..client import Optropic


class Audit:
    """Interact with the immutable audit log."""

    def __init__(self, client: Optropic) -> None:
        self._client = client

    def list(self, params: Optional[ListAuditParams] = None) -> Dict[str, Any]:
        """List audit events with optional filtering and pagination."""
        query = asdict(params) if params else None
        return self._client._request("GET", "/audit", params=query)

    def get(self, event_id: str) -> Dict[str, Any]:
        """Retrieve a single audit event by ID."""
        return self._client._request("GET", f"/audit/{event_id}")

    def create(
        self,
        event_type: str,
        resource_id: Optional[str] = None,
        resource_type: Optional[str] = None,
        details: Optional[Dict[str, Any]] = None,
    ) -> Dict[str, Any]:
        """Record a custom audit event."""
        body: Dict[str, Any] = {"event_type": event_type}
        if resource_id is not None:
            body["resource_id"] = resource_id
        if resource_type is not None:
            body["resource_type"] = resource_type
        if details is not None:
            body["details"] = details
        return self._client._request("POST", "/audit", json=body)
