"""Webhooks resource — /webhooks endpoints."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

from curvestone.types.webhook import Webhook, WebhookCreated

if TYPE_CHECKING:
    from curvestone._client import AsyncCurvestone, Curvestone


class SyncWebhooks:
    def __init__(self, client: Curvestone) -> None:
        self._client = client

    def create(
        self,
        *,
        url: str,
        events: list[str],
        description: str | None = None,
    ) -> WebhookCreated:
        """Register a new webhook endpoint."""
        body: dict[str, Any] = {"url": url, "events": events}
        if description is not None:
            body["description"] = description
        resp = self._client._request("POST", "/webhooks", json=body)
        return WebhookCreated.model_validate(resp)

    def retrieve(self, webhook_id: str) -> Webhook:
        """Get a webhook by ID."""
        resp = self._client._request("GET", f"/webhooks/{webhook_id}")
        return Webhook.model_validate(resp)

    def list(self) -> list[Webhook]:
        """List all webhooks."""
        resp = self._client._request("GET", "/webhooks")
        return [Webhook.model_validate(w) for w in (resp or [])]

    def update(
        self,
        webhook_id: str,
        *,
        url: str | None = None,
        events: list[str] | None = None,
        description: str | None = None,
        status: str | None = None,
    ) -> Webhook:
        """Update a webhook."""
        body: dict[str, Any] = {}
        if url is not None:
            body["url"] = url
        if events is not None:
            body["events"] = events
        if description is not None:
            body["description"] = description
        if status is not None:
            body["status"] = status
        resp = self._client._request("PATCH", f"/webhooks/{webhook_id}", json=body)
        return Webhook.model_validate(resp)

    def delete(self, webhook_id: str) -> None:
        """Delete a webhook."""
        self._client._request("DELETE", f"/webhooks/{webhook_id}")

    def test(self, webhook_id: str) -> dict:
        """Send a test event to a webhook."""
        resp = self._client._request("POST", f"/webhooks/{webhook_id}/test")
        return resp or {}


class AsyncWebhooks:
    def __init__(self, client: AsyncCurvestone) -> None:
        self._client = client

    async def create(
        self,
        *,
        url: str,
        events: list[str],
        description: str | None = None,
    ) -> WebhookCreated:
        """Register a new webhook endpoint."""
        body: dict[str, Any] = {"url": url, "events": events}
        if description is not None:
            body["description"] = description
        resp = await self._client._request("POST", "/webhooks", json=body)
        return WebhookCreated.model_validate(resp)

    async def retrieve(self, webhook_id: str) -> Webhook:
        """Get a webhook by ID."""
        resp = await self._client._request("GET", f"/webhooks/{webhook_id}")
        return Webhook.model_validate(resp)

    async def list(self) -> list[Webhook]:
        """List all webhooks."""
        resp = await self._client._request("GET", "/webhooks")
        return [Webhook.model_validate(w) for w in (resp or [])]

    async def update(
        self,
        webhook_id: str,
        *,
        url: str | None = None,
        events: list[str] | None = None,
        description: str | None = None,
        status: str | None = None,
    ) -> Webhook:
        """Update a webhook."""
        body: dict[str, Any] = {}
        if url is not None:
            body["url"] = url
        if events is not None:
            body["events"] = events
        if description is not None:
            body["description"] = description
        if status is not None:
            body["status"] = status
        resp = await self._client._request("PATCH", f"/webhooks/{webhook_id}", json=body)
        return Webhook.model_validate(resp)

    async def delete(self, webhook_id: str) -> None:
        """Delete a webhook."""
        await self._client._request("DELETE", f"/webhooks/{webhook_id}")

    async def test(self, webhook_id: str) -> dict:
        """Send a test event to a webhook."""
        resp = await self._client._request("POST", f"/webhooks/{webhook_id}/test")
        return resp or {}
