"""Pytest fixtures for webhook tests."""

from __future__ import annotations

from collections.abc import Mapping
from typing import cast
from uuid import uuid4

import httpx
import pytest

from noteflow.domain.webhooks import WebhookConfig, WebhookEventType
from noteflow.infrastructure.webhooks import WebhookExecutor


class HeaderCapture:
    """Captures HTTP headers from mocked requests."""

    def __init__(self) -> None:
        self.headers: dict[str, str] = {}

    async def capture_request(self, *args: object, **kwargs: object) -> httpx.Response:
        """Mock request handler that captures headers."""
        headers_raw = kwargs.get("headers", {})
        assert isinstance(headers_raw, Mapping), "Headers should be Mapping"
        # cast required: httpx HeaderTypes is Mapping[str, str] | Mapping[bytes, bytes]
        # WebhookExecutor always passes str headers per _build_headers() implementation
        headers_mapping = cast(Mapping[str, str], headers_raw)
        self.headers.update(headers_mapping)
        return httpx.Response(200)


@pytest.fixture
def header_capture() -> HeaderCapture:
    """Create a header capture instance for tests."""
    return HeaderCapture()


@pytest.fixture
def executor() -> WebhookExecutor:
    """Create a WebhookExecutor instance."""
    return WebhookExecutor(max_retries=3, timeout_seconds=5.0)


@pytest.fixture
def enabled_config() -> WebhookConfig:
    """Create an enabled webhook config for all events."""
    return WebhookConfig.create(
        workspace_id=uuid4(),
        url="https://example.com/webhook",
        events=[
            WebhookEventType.MEETING_COMPLETED,
            WebhookEventType.SUMMARY_GENERATED,
        ],
        name="Test Webhook",
    )


@pytest.fixture
def disabled_config() -> WebhookConfig:
    """Create a disabled webhook config."""
    workspace_id = uuid4()
    now = WebhookConfig.create(workspace_id, "", [WebhookEventType.MEETING_COMPLETED]).created_at
    return WebhookConfig(
        id=uuid4(),
        workspace_id=workspace_id,
        url="https://example.com/webhook",
        events=frozenset([WebhookEventType.MEETING_COMPLETED]),
        name="Disabled Webhook",
        enabled=False,
        created_at=now,
        updated_at=now,
    )


@pytest.fixture
def signed_config() -> WebhookConfig:
    """Create a webhook config with HMAC secret."""
    return WebhookConfig.create(
        workspace_id=uuid4(),
        url="https://example.com/webhook",
        events=[WebhookEventType.MEETING_COMPLETED],
        name="Signed Webhook",
        secret="test-secret-key",
    )
