"""Integration tests for app.api.v1.ws — WebSocket feed + status endpoint."""

import json
import uuid

import httpx
import pytest

from app.main import app
from starlette.testclient import TestClient


@pytest.mark.asyncio
async def test_ws_status(client):
    """GET /ws/status returns online user counts."""
    r = await client.get("/api/v1/ws/status")
    assert r.status_code == 200
    data = r.json()
    assert "online_users" in data
    assert "online_connections" in data


def test_ws_invalid_token():
    """WebSocket with invalid token closes with 4001."""
    sync_client = TestClient(app)
    with pytest.raises(Exception):
        with sync_client.websocket_connect("/api/v1/ws/feed?token=badtoken") as ws:
            ws.receive_json()


@pytest.mark.asyncio
async def test_ws_valid_token(auth_headers, live_server, server_port):
    """WebSocket with valid token connects successfully."""
    import websockets

    token = auth_headers["Authorization"].replace("Bearer ", "")
    async with websockets.connect(
        f"ws://127.0.0.1:{server_port}/api/v1/ws/feed?token={token}"
    ) as ws:
        raw = await ws.recv()
        data = json.loads(raw)
        assert data["type"] == "connected"
        assert "user_id" in data
        assert "online_users" in data


@pytest.mark.asyncio
async def test_ws_ping_pong(auth_headers, live_server, server_port):
    """WebSocket responds to ping with pong."""
    import websockets

    token = auth_headers["Authorization"].replace("Bearer ", "")
    async with websockets.connect(
        f"ws://127.0.0.1:{server_port}/api/v1/ws/feed?token={token}"
    ) as ws:
        raw = await ws.recv()  # connected message
        data = json.loads(raw)
        assert data["type"] == "connected"

        await ws.send("ping")
        pong_raw = await ws.recv()
        pong = json.loads(pong_raw)
        assert pong["type"] == "pong"


@pytest.mark.asyncio
async def test_ws_refresh_token_rejected(live_server, server_port):
    """WebSocket with refresh token (not access) closes with 4001."""
    import websockets

    async with httpx.AsyncClient(base_url=f"http://127.0.0.1:{server_port}") as ac:
        email = f"t{uuid.uuid4().hex[:6]}@test.cn"
        resp = await ac.post("/api/v1/auth/register", json={
            "email": email, "password": "Test1234", "display_name": "TestWS",
        })
        assert resp.status_code == 200
        refresh_token = resp.json()["token"]["refresh_token"]

    with pytest.raises(Exception):
        async with websockets.connect(
            f"ws://127.0.0.1:{server_port}/api/v1/ws/feed?token={refresh_token}"
        ) as ws:
            await ws.recv()
