"""CH-SRV-001 — list server → update field → persisted."""

from __future__ import annotations

from unittest.mock import AsyncMock

import pytest

from server.api.dependencies import get_server_service
from server.api.schemas import ServerUpdate
from server.api.servers import get_server, update_server
from server.infrastructure.database.server_repo import ServerRepositoryImpl

pytestmark = pytest.mark.chain


@pytest.mark.asyncio
async def test_server_list_update_persisted(
    db_session,
    test_admin,
    test_server,
    mock_request,
    monkeypatch,
):
    mock_request.state.db = db_session
    service = await get_server_service(mock_request)

    mock_redis = AsyncMock()
    mock_redis.hgetall = AsyncMock(return_value={})
    monkeypatch.setattr("server.api.servers.get_redis", lambda: mock_redis)

    detail = await get_server(test_server.id, test_admin["admin"], service)
    assert detail["id"] == test_server.id

    new_desc = "chain-integration-desc"
    updated = await update_server(
        mock_request,
        test_server.id,
        ServerUpdate(description=new_desc),
        test_admin["admin"],
        service,
        db_session,
    )
    assert updated.get("description") == new_desc

    repo = ServerRepositoryImpl(db_session)
    row = await repo.get_by_id(test_server.id)
    assert row is not None
    assert row.description == new_desc
