from tests.conftest import make_app, make_settings, running


async def test_health_ok_when_database_and_livekit_are_up(client):
    response = await client.get("/health")

    assert response.status_code == 200
    assert response.json() == {"status": "ok", "checks": {"database": "ok", "livekit": "ok"}}


async def test_health_reports_livekit_down(client, fake_livekit):
    fake_livekit.healthy = False

    response = await client.get("/health")

    assert response.status_code == 503
    assert response.json() == {
        "status": "degraded",
        "checks": {"database": "ok", "livekit": "down"},
    }


async def test_health_reports_database_down_without_details():
    # Nothing listens on port 1, so the connection is refused straight away.
    settings = make_settings(database_url="postgresql+asyncpg://user:pass@127.0.0.1:1/db")
    app = make_app(settings)

    async with running(app) as client:
        response = await client.get("/health")

    assert response.status_code == 503
    assert response.json() == {
        "status": "degraded",
        "checks": {"database": "down", "livekit": "ok"},
    }


async def test_livekit_adapter_is_closed_on_shutdown(fake_livekit):
    app = make_app(livekit=fake_livekit)

    async with running(app):
        assert not fake_livekit.closed

    assert fake_livekit.closed
