"""Webhook ORM to domain entity converters."""

from __future__ import annotations

from typing import TYPE_CHECKING, cast

from noteflow.domain.webhooks import (
    WebhookConfig,
    WebhookDelivery,
    WebhookEventType,
    WebhookPayloadDict,
)

if TYPE_CHECKING:
    from noteflow.infrastructure.persistence.models.integrations.webhook import (
        WebhookConfigModel,
        WebhookDeliveryModel,
    )


class WebhookConverter:
    """Convert between webhook domain objects and ORM models."""

    @staticmethod
    def config_to_domain(model: WebhookConfigModel) -> WebhookConfig:
        """Convert ORM WebhookConfigModel to domain WebhookConfig.

        Args:
            model: SQLAlchemy WebhookConfigModel instance.

        Returns:
            Domain WebhookConfig entity.
        """
        return WebhookConfig(
            id=model.id,
            workspace_id=model.workspace_id,
            name=model.name,
            url=model.url,
            events=frozenset(WebhookEventType(e) for e in model.events),
            secret=model.secret,
            enabled=model.enabled,
            timeout_ms=model.timeout_ms,
            max_retries=model.max_retries,
            created_at=model.created_at,
            updated_at=model.updated_at,
        )

    @staticmethod
    def config_to_orm_kwargs(entity: WebhookConfig) -> dict[str, object]:
        """Convert domain WebhookConfig to ORM model kwargs.

        Returns a dict of kwargs rather than instantiating WebhookConfigModel
        directly to avoid circular imports and allow the repository to
        handle ORM construction.

        Args:
            entity: Domain WebhookConfig.

        Returns:
            Kwargs dict for WebhookConfigModel construction.
        """
        return {
            "id": entity.id,
            "workspace_id": entity.workspace_id,
            "name": entity.name,
            "url": entity.url,
            "events": [e.value for e in entity.events],
            "secret": entity.secret,
            "enabled": entity.enabled,
            "timeout_ms": entity.timeout_ms,
            "max_retries": entity.max_retries,
            "created_at": entity.created_at,
            "updated_at": entity.updated_at,
        }

    @staticmethod
    def delivery_to_domain(model: WebhookDeliveryModel) -> WebhookDelivery:
        """Convert ORM WebhookDeliveryModel to domain WebhookDelivery.

        Args:
            model: SQLAlchemy WebhookDeliveryModel instance.

        Returns:
            Domain WebhookDelivery entity.
        """
        return WebhookDelivery(
            id=model.id,
            webhook_id=model.webhook_id,
            event_type=WebhookEventType(model.event_type),
            payload=cast(WebhookPayloadDict, dict(model.payload)),
            status_code=model.status_code,
            response_body=model.response_body,
            error_message=model.error_message,
            attempt_count=model.attempt_count,
            duration_ms=model.duration_ms,
            delivered_at=model.delivered_at,
        )

    @staticmethod
    def delivery_to_orm_kwargs(entity: WebhookDelivery) -> dict[str, object]:
        """Convert domain WebhookDelivery to ORM model kwargs.

        Args:
            entity: Domain WebhookDelivery.

        Returns:
            Kwargs dict for WebhookDeliveryModel construction.
        """
        return {
            "id": entity.id,
            "webhook_id": entity.webhook_id,
            "event_type": entity.event_type.value,
            "payload": entity.payload,
            "status_code": entity.status_code,
            "response_body": entity.response_body,
            "error_message": entity.error_message,
            "attempt_count": entity.attempt_count,
            "duration_ms": entity.duration_ms,
            "delivered_at": entity.delivered_at,
        }
