"""
Webhook resource for managing webhooks.
"""

from typing import Any, Dict, List, Optional

from emailr.http import AsyncHttpClient, HttpClient
from emailr.types import (
    CreateWebhookRequest,
    SuccessResponse,
    Webhook,
    WebhookDelivery,
    WebhookToggleResponse,
)


class WebhooksResource:
    """Synchronous webhook resource for managing webhooks."""

    def __init__(self, http: HttpClient) -> None:
        self._http = http

    def create(
        self,
        name: str,
        url: str,
        type: str,
        *,
        inbox_ids: Optional[List[str]] = None,
    ) -> Webhook:
        """
        Create a new webhook.

        Args:
            name: Webhook name
            url: Webhook URL
            type: Webhook type ('transactional', 'domain', 'receiving')
            inbox_ids: Optional inbox IDs for 'receiving' type webhooks

        Returns:
            Created webhook
        """
        request = CreateWebhookRequest(name=name, url=url, type=type, inbox_ids=inbox_ids)
        data = self._http.post("/v1/webhooks", request.to_dict())
        return Webhook.from_dict(data)

    def list(self) -> List[Webhook]:
        """
        List all webhooks.

        Returns:
            List of webhooks
        """
        data = self._http.get("/v1/webhooks")
        if isinstance(data, list):
            return [Webhook.from_dict(w) for w in data]
        return [Webhook.from_dict(w) for w in data.get("data", data)]

    def delete(self, id: str) -> SuccessResponse:
        """
        Delete a webhook.

        Args:
            id: Webhook ID

        Returns:
            Success response
        """
        data = self._http.delete(f"/v1/webhooks/{id}")
        return SuccessResponse(success=data.get("success", True))

    def toggle(self, id: str) -> WebhookToggleResponse:
        """
        Toggle a webhook's active state (enable/disable).

        Args:
            id: Webhook ID

        Returns:
            Toggle response with new active status
        """
        data = self._http.put(f"/v1/webhooks/{id}/toggle")
        return WebhookToggleResponse.from_dict(data)

    def list_deliveries(self, id: str) -> List[WebhookDelivery]:
        """
        List webhook deliveries.

        Args:
            id: Webhook ID

        Returns:
            List of webhook deliveries
        """
        data = self._http.get(f"/v1/webhooks/{id}/deliveries")
        if isinstance(data, list):
            return [WebhookDelivery.from_dict(d) for d in data]
        return [WebhookDelivery.from_dict(d) for d in data.get("data", data)]


class AsyncWebhooksResource:
    """Asynchronous webhook resource for managing webhooks."""

    def __init__(self, http: AsyncHttpClient) -> None:
        self._http = http

    async def create(
        self,
        name: str,
        url: str,
        type: str,
        *,
        inbox_ids: Optional[List[str]] = None,
    ) -> Webhook:
        """Create a new webhook."""
        request = CreateWebhookRequest(name=name, url=url, type=type, inbox_ids=inbox_ids)
        data = await self._http.post("/v1/webhooks", request.to_dict())
        return Webhook.from_dict(data)

    async def list(self) -> List[Webhook]:
        """List all webhooks."""
        data = await self._http.get("/v1/webhooks")
        if isinstance(data, list):
            return [Webhook.from_dict(w) for w in data]
        return [Webhook.from_dict(w) for w in data.get("data", data)]

    async def delete(self, id: str) -> SuccessResponse:
        """Delete a webhook."""
        data = await self._http.delete(f"/v1/webhooks/{id}")
        return SuccessResponse(success=data.get("success", True))

    async def toggle(self, id: str) -> WebhookToggleResponse:
        """Toggle a webhook's active state (enable/disable)."""
        data = await self._http.put(f"/v1/webhooks/{id}/toggle")
        return WebhookToggleResponse.from_dict(data)

    async def list_deliveries(self, id: str) -> List[WebhookDelivery]:
        """List webhook deliveries."""
        data = await self._http.get(f"/v1/webhooks/{id}/deliveries")
        if isinstance(data, list):
            return [WebhookDelivery.from_dict(d) for d in data]
        return [WebhookDelivery.from_dict(d) for d in data.get("data", data)]
