"""CH-PUSH-001 — POST accepted → sync WebSocket progress channel."""

from __future__ import annotations

from unittest.mock import MagicMock

import pytest

from server.api.schemas import SyncFiles
from server.api.sync_v2 import sync_files

pytestmark = pytest.mark.chain


@pytest.mark.asyncio
async def test_push_accepted_then_sync_progress_event(
    db_session,
    test_admin,
    test_server,
    monkeypatch,
):
    scheduled: list[dict] = []

    def fake_schedule(**kwargs):
        scheduled.append(kwargs)

    monkeypatch.setattr(
        "server.background.sync_push_runner.schedule_sync_files",
        fake_schedule,
    )
    monkeypatch.setattr(
        "server.application.services.sync_engine_v2._nexus_source_path",
        lambda _path: "/tmp/nexus-test-src",
    )

    request = MagicMock()
    request.state.db = db_session
    request.client = MagicMock()
    request.client.host = "127.0.0.1"

    batch_id = "112233445566"
    payload = SyncFiles(
        server_ids=[test_server.id],
        source_path="/tmp/nexus-test-src",
        batch_id=batch_id,
    )

    body = await sync_files(payload, request, test_admin["admin"])
    assert body["accepted"] is True
    assert len(scheduled) == 1

    from server.api import websocket as ws

    calls: list[tuple[str, dict]] = []

    async def capture_sync(msg):
        calls.append(("sync", msg))

    async def capture_alert(msg):
        calls.append(("alert", msg))

    monkeypatch.setattr(ws, "_dispatch_sync_message", capture_sync)
    monkeypatch.setattr(ws, "_dispatch_ws_message", capture_alert)

    await ws.broadcast_sync_progress(
        batch_id=batch_id,
        server_id=test_server.id,
        server_name=test_server.name,
        status="running",
        completed=0,
        failed=0,
        total=1,
    )

    assert len(calls) == 1
    assert calls[0][0] == "sync"
    assert calls[0][1]["type"] == "sync_progress"
    assert calls[0][1]["batch_id"] == batch_id
