"""Recording transport for fixture-driven Webhooks tests."""

from __future__ import annotations

from typing import Any

from test_support.transport_base import BaseRecordingTransport
from test_support.transport_helpers import dump_model
from timeback_common import WebhookPaths

from ..types.api import Webhook, WebhookFilter


def create_recording_transport(
    fail_request: dict[str, Any] | None = None,
    transport_config: dict[str, Any] | None = None,
) -> BaseRecordingTransport:
    """Create a transport-like object that records calls and returns stub responses."""
    return _WebhooksRecordingTransport(fail_request=fail_request, transport_config=transport_config)


class _WebhooksRecordingTransport(BaseRecordingTransport):
    """Webhooks-specific recording transport with webhook paths and stubs."""

    def __init__(self, **kwargs: Any) -> None:
        super().__init__(**kwargs)
        self.paths = self._build_paths()

    def _default_get_stub(self, path: str) -> dict[str, Any]:
        if "/webhook-filters" in path:
            if "/webhook/" in path or path == self.paths.webhook_filter_list:
                return {"filters": [dump_model(_stub_filter())]}
            return {"filter": dump_model(_stub_filter())}

        if path == self.paths.webhook_list or path.startswith(f"{self.paths.webhook_list}?"):
            return {"webhooks": [dump_model(_stub_webhook())]}
        return {"webhook": dump_model(_stub_webhook())}

    def _default_post_stub(self, path: str) -> dict[str, Any]:
        if "/webhook-filters" in path:
            return {"filter": dump_model(_stub_filter())}
        return {"webhook": dump_model(_stub_webhook())}

    def _default_put_stub(self, path: str) -> dict[str, Any]:
        if "/webhook-filters" in path:
            return {"filter": dump_model(_stub_filter())}
        return {"webhook": dump_model(_stub_webhook())}

    def _default_delete_stub(self, path: str) -> dict[str, Any]:  # noqa: ARG002
        return {"message": "deleted"}

    def _build_paths(self) -> WebhookPaths:
        defaults: dict[str, str | None] = {
            "webhook_list": "/webhooks/",
            "webhook_get": "/webhooks/{id}",
            "webhook_create": "/webhooks/",
            "webhook_update": "/webhooks/{id}",
            "webhook_delete": "/webhooks/{id}",
            "webhook_activate": "/webhooks/{id}/activate",
            "webhook_deactivate": "/webhooks/{id}/deactivate",
            "webhook_filter_list": "/webhook-filters/",
            "webhook_filter_get": "/webhook-filters/{id}",
            "webhook_filter_create": "/webhook-filters/",
            "webhook_filter_update": "/webhook-filters/{id}",
            "webhook_filter_delete": "/webhook-filters/{id}",
            "webhook_filters_by_webhook": "/webhook-filters/webhook/{webhookId}",
        }

        exclude_map = {
            "webhookList": "webhook_list",
            "webhookGet": "webhook_get",
            "webhookCreate": "webhook_create",
            "webhookUpdate": "webhook_update",
            "webhookDelete": "webhook_delete",
            "webhookActivate": "webhook_activate",
            "webhookDeactivate": "webhook_deactivate",
            "webhookFilterList": "webhook_filter_list",
            "webhookFilterGet": "webhook_filter_get",
            "webhookFilterCreate": "webhook_filter_create",
            "webhookFilterUpdate": "webhook_filter_update",
            "webhookFilterDelete": "webhook_filter_delete",
            "webhookFiltersByWebhook": "webhook_filters_by_webhook",
        }

        self.apply_exclude_paths(
            defaults, exclude_map, self._transport_config.get("excludePaths", [])
        )

        return WebhookPaths(
            webhook_list=defaults["webhook_list"] or "",
            webhook_get=defaults["webhook_get"] or "",
            webhook_create=defaults["webhook_create"] or "",
            webhook_update=defaults["webhook_update"] or "",
            webhook_delete=defaults["webhook_delete"] or "",
            webhook_activate=defaults["webhook_activate"] or "",
            webhook_deactivate=defaults["webhook_deactivate"] or "",
            webhook_filter_list=defaults["webhook_filter_list"] or "",
            webhook_filter_get=defaults["webhook_filter_get"] or "",
            webhook_filter_create=defaults["webhook_filter_create"] or "",
            webhook_filter_update=defaults["webhook_filter_update"] or "",
            webhook_filter_delete=defaults["webhook_filter_delete"] or "",
            webhook_filters_by_webhook=defaults["webhook_filters_by_webhook"] or "",
        )


def _stub_webhook() -> Webhook:
    return Webhook(
        id="wh-001",
        name="Test Webhook",
        targetUrl="https://example.com/events",
        secret="secret",
        active=True,
        sensor=None,
        description=None,
        created_at="2024-01-01T00:00:00Z",
        updated_at=None,
        deleted_at=None,
    )


def _stub_filter() -> WebhookFilter:
    return WebhookFilter(
        id="wf-001",
        webhookId="wh-001",
        filterKey="type",
        filterValue="Event",
        filterType="string",
        filterOperator="eq",
        active=True,
        created_at="2024-01-01T00:00:00Z",
        updated_at=None,
        deleted_at=None,
    )
