from __future__ import annotations

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

from ..types import CreateWebhookParams, WebhookDelivery, WebhookEndpoint

if TYPE_CHECKING:
    from ..client import Optropic


class Webhooks:
    """Manage webhook endpoints and inspect delivery history."""

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

    def create(self, params: CreateWebhookParams) -> Dict[str, Any]:
        """Register a new webhook endpoint.

        Returns the endpoint together with the signing secret.
        """
        return self._client._request("POST", "/webhooks", json=asdict(params))

    def list(self) -> List[WebhookEndpoint]:
        """List all registered webhook endpoints."""
        data = self._client._request("GET", "/webhooks")
        return [WebhookEndpoint(**item) for item in data]

    def delete(self, endpoint_id: str) -> Dict[str, Any]:
        """Delete a webhook endpoint."""
        return self._client._request("DELETE", f"/webhooks/{endpoint_id}")

    def list_deliveries(self, endpoint_id: str) -> List[WebhookDelivery]:
        """List delivery attempts for a specific webhook endpoint."""
        data = self._client._request("GET", f"/webhooks/{endpoint_id}/deliveries")
        return [WebhookDelivery(**item) for item in data]
