"""IT-AGT-001 — agent heartbeat accepts valid per-server API key."""

from __future__ import annotations

from unittest.mock import AsyncMock

import pytest

from server.api.agent import receive_heartbeat
from server.api.dependencies import get_server_service
from server.api.schemas import AgentHeartbeat

pytestmark = pytest.mark.integration


@pytest.mark.asyncio
async def test_heartbeat_ok_with_server_key(
    db_session,
    test_server,
    mock_request,
    monkeypatch,
):
    api_key = "test-agent-key-001"
    test_server.agent_api_key = api_key
    await db_session.commit()

    mock_redis = AsyncMock()
    mock_redis.set = AsyncMock()
    mock_redis.get = AsyncMock(return_value=None)
    mock_redis.smembers = AsyncMock(return_value=set())
    mock_redis.sadd = AsyncMock()
    mock_redis.srem = AsyncMock()
    mock_redis.delete = AsyncMock()
    monkeypatch.setattr("server.api.agent.get_redis", lambda: mock_redis)
    monkeypatch.setattr("server.api.agent.broadcast_alert", AsyncMock())
    monkeypatch.setattr("server.api.agent.broadcast_recovery", AsyncMock())
    monkeypatch.setattr("server.api.agent.send_telegram_system_alert", AsyncMock())

    mock_request.state.db = db_session
    service = await get_server_service(mock_request)

    payload = AgentHeartbeat(
        server_id=test_server.id,
        is_online=True,
        system_info={"cpu_usage": 10.0, "mem_usage": 20.0, "disk_usage": 30.0},
        agent_version="1.0.0",
    )

    result = await receive_heartbeat(payload, api_key=api_key, service=service)

    assert result.get("status") in ("ok", "received", "success") or "server_id" in result
