"""Webhook models for the Danube SDK."""

from typing import Any, Dict, List, Optional

from pydantic import BaseModel


class WebhookResponse(BaseModel):
    """A webhook configuration."""

    id: str = ""
    url: str = ""
    events: List[str] = []
    is_active: bool = True
    description: Optional[str] = None
    created_at: Optional[str] = None
    updated_at: Optional[str] = None

    model_config = {"extra": "ignore"}

    @classmethod
    def from_api_response(cls, data: Dict[str, Any]) -> "WebhookResponse":
        return cls(
            id=data.get("id", ""),
            url=data.get("url", ""),
            events=data.get("events", []),
            is_active=data.get("is_active", True),
            description=data.get("description"),
            created_at=data.get("created_at"),
            updated_at=data.get("updated_at"),
        )


class WebhookCreateResponse(WebhookResponse):
    """Webhook returned on creation, includes the signing secret."""

    secret: str = ""

    @classmethod
    def from_api_response(cls, data: Dict[str, Any]) -> "WebhookCreateResponse":
        return cls(
            id=data.get("id", ""),
            url=data.get("url", ""),
            events=data.get("events", []),
            is_active=data.get("is_active", True),
            description=data.get("description"),
            created_at=data.get("created_at"),
            updated_at=data.get("updated_at"),
            secret=data.get("secret", ""),
        )


class WebhookDeliveryResponse(BaseModel):
    """A webhook delivery attempt record."""

    id: str = ""
    webhook_id: str = ""
    event_type: str = ""
    payload: Dict[str, Any] = {}
    status: str = ""
    response_status: Optional[int] = None
    response_body: Optional[str] = None
    attempts: int = 0
    delivered_at: Optional[str] = None
    created_at: Optional[str] = None

    model_config = {"extra": "ignore"}

    @classmethod
    def from_api_response(cls, data: Dict[str, Any]) -> "WebhookDeliveryResponse":
        return cls(
            id=data.get("id", ""),
            webhook_id=data.get("webhook_id", ""),
            event_type=data.get("event_type", ""),
            payload=data.get("payload", {}),
            status=data.get("status", ""),
            response_status=data.get("response_status"),
            response_body=data.get("response_body"),
            attempts=data.get("attempts", 0),
            delivered_at=data.get("delivered_at"),
            created_at=data.get("created_at"),
        )
