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


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


def test_settings_load_from_env(monkeypatch):
    _apply_env(monkeypatch)

    # Import inside test to pick up monkeypatched env
    import importlib

    import app.config as config_module

    importlib.reload(config_module)

    s = config_module.Settings()
    assert s.database_url == "postgresql+asyncpg://u:p@localhost/db"
    assert s.s3_bucket_name == "test-bucket"
    assert s.max_upload_bytes == 52428800  # default
    assert s.jwt_secret_key == "test-secret"
    assert s.jwt_expiry_seconds == 86400  # default
    assert s.owner_username == "admin"


def test_settings_max_upload_bytes_override(monkeypatch):
    _apply_env(monkeypatch, {"MAX_UPLOAD_BYTES": "10485760"})

    import importlib

    import app.config as config_module

    importlib.reload(config_module)

    s = config_module.Settings()
    assert s.max_upload_bytes == 10485760


def test_settings_jwt_expiry_override(monkeypatch):
    _apply_env(monkeypatch, {"JWT_EXPIRY_SECONDS": "3600"})

    import importlib

    import app.config as config_module

    importlib.reload(config_module)

    s = config_module.Settings()
    assert s.jwt_expiry_seconds == 3600


def test_api_docs_enabled_default(monkeypatch):
    _apply_env(monkeypatch)

    import importlib

    import app.config as config_module

    importlib.reload(config_module)

    s = config_module.Settings()
    assert s.api_docs_enabled is True


def test_api_docs_enabled_false(monkeypatch):
    _apply_env(monkeypatch, {"API_DOCS_ENABLED": "false"})

    import importlib

    import app.config as config_module

    importlib.reload(config_module)

    s = config_module.Settings()
    assert s.api_docs_enabled is False


def test_api_docs_invalid_value_defaults_to_enabled(monkeypatch):
    _apply_env(monkeypatch, {"API_DOCS_ENABLED": "not-a-bool"})

    import importlib

    import app.config as config_module

    importlib.reload(config_module)

    s = config_module.Settings()
    assert s.api_docs_enabled is True
