"""Security validation — anonymous denial when auth required."""
from __future__ import annotations

import os

import pytest
from httpx import ASGITransport, AsyncClient


@pytest.mark.asyncio
async def test_auth_required_denies_anonymous(db_setup):
    os.environ["AUTH_REQUIRED"] = "true"
    from app.core.config import get_settings

    get_settings.cache_clear()
    import app.core.config as config_mod
    import app.core.security as security_mod
    import app.api.permissions as perm_mod

    config_mod.settings = get_settings()
    security_mod.settings = config_mod.settings
    perm_mod.settings = config_mod.settings

    from app.main import create_app

    app = create_app()
    transport = ASGITransport(app=app)
    try:
        async with AsyncClient(transport=transport, base_url="http://testserver") as client:
            res = await client.get(
                "/api/v1/clinics",
                headers={"X-Tenant-ID": "11111111-1111-1111-1111-111111111111"},
            )
            assert res.status_code == 401
    finally:
        os.environ["AUTH_REQUIRED"] = "false"
        get_settings.cache_clear()
        config_mod.settings = get_settings()
        security_mod.settings = config_mod.settings
        perm_mod.settings = config_mod.settings
