import importlib

from starlette.testclient import TestClient

from app.config import get_settings

_BASE_ENV = {
    "DATABASE_URL": "postgresql+asyncpg://u:p@localhost/db",
    "JWT_SECRET_KEY": "test-secret",
    "OWNER_USERNAME": "admin",
    "OWNER_PASSWORD": "password",
    "S3_ENDPOINT_URL": "http://localhost:9000",
    "S3_BUCKET_NAME": "test-bucket",
    "S3_ACCESS_KEY_ID": "key",
    "S3_SECRET_ACCESS_KEY": "secret",
}


def _set_env(monkeypatch, extra=None):
    for k, v in {**_BASE_ENV, **(extra or {})}.items():
        monkeypatch.setenv(k, v)


def test_docs_hidden_when_flag_disabled(monkeypatch):
    _set_env(monkeypatch, {"API_DOCS_ENABLED": "false"})
    get_settings.cache_clear()
    import app.main as m

    importlib.reload(m)
    client = TestClient(m.app, raise_server_exceptions=False)
    assert client.get("/docs").status_code == 404
    assert client.get("/redoc").status_code == 404
    assert client.get("/openapi.json").status_code == 404
    assert client.get("/api/v1/health").status_code == 200
    get_settings.cache_clear()


def test_docs_visible_when_flag_enabled(monkeypatch):
    _set_env(monkeypatch, {"API_DOCS_ENABLED": "true"})
    get_settings.cache_clear()
    import app.main as m

    importlib.reload(m)
    client = TestClient(m.app, raise_server_exceptions=False)
    assert client.get("/docs").status_code == 200
    assert client.get("/redoc").status_code == 200
    assert client.get("/openapi.json").status_code == 200
    get_settings.cache_clear()
