"""
Integration tests for WS_DELIVERY domain payload routing.

Author: Vasiliy Zdanovskiy
email: vasilyvz@gmail.com
"""

from __future__ import annotations

from typing import Any, Dict, List

import pytest
from fastapi import FastAPI

from mcp_proxy_adapter.core.job_push.events import (
    EVENT_DELIVERY_COMPLETED,
    EVENT_JOB_COMPLETED,
)
from mcp_proxy_adapter.core.job_push.lifespan_wiring import _make_listener
from mcp_proxy_adapter.core.job_push.notifier import NotificationDomain
from mcp_proxy_adapter.core.job_push.subscriptions import (
    Subscriber,
    SubscriberRegistry,
    SubscriptionCategory,
)


class MockSubscriber(Subscriber):
    """Mock subscriber that records sent payloads."""

    def __init__(self) -> None:
        """Initialize empty payload list."""
        self.sent_payloads: List[Dict[str, Any]] = []

    async def send(self, payload: dict) -> None:
        """Record payload."""
        self.sent_payloads.append(payload.copy())


@pytest.mark.asyncio
async def test_ws_delivery_domain_yields_delivery_completed_payload() -> None:
    """Test that WS_DELIVERY domain produces delivery_* event payloads."""
    app = FastAPI()
    registry = SubscriberRegistry()
    app.state.job_push_registry = registry

    subscriber = MockSubscriber()
    await registry.subscribe("ws-42", SubscriptionCategory.WS_DELIVERY, subscriber)

    listener = _make_listener(app)
    await listener(
        NotificationDomain.WS_DELIVERY,
        "ws-42",
        "completed",
        {"result": "ok"},
        None,
        0,
        "",
    )

    assert len(subscriber.sent_payloads) == 1
    payload = subscriber.sent_payloads[0]
    assert payload["event"] == EVENT_DELIVERY_COMPLETED
    assert payload["ws_id"] == "ws-42"
    assert payload["result"] == {"result": "ok"}


@pytest.mark.asyncio
async def test_queue_job_domain_yields_job_completed_payload() -> None:
    """Test that QUEUE_JOB domain produces job_* event payloads."""
    app = FastAPI()
    registry = SubscriberRegistry()
    app.state.job_push_registry = registry

    subscriber = MockSubscriber()
    await registry.subscribe("job-123", SubscriptionCategory.QUEUE_JOB, subscriber)

    listener = _make_listener(app)
    await listener(
        NotificationDomain.QUEUE_JOB,
        "job-123",
        "completed",
        {"result": "ok"},
        None,
        0,
        "",
    )

    assert len(subscriber.sent_payloads) == 1
    payload = subscriber.sent_payloads[0]
    assert payload["event"] == EVENT_JOB_COMPLETED
    assert payload["job_id"] == "job-123"
    assert payload["result"] == {"result": "ok"}
