import pytest

from app.config import config


def test_datasource_pool_defaults_are_bounded(monkeypatch):
    for name in (
        "DATASOURCE_POOL_SIZE",
        "DATASOURCE_MAX_OVERFLOW",
        "DATASOURCE_POOL_TIMEOUT",
        "DATASOURCE_POOL_RECYCLE",
        "DATASOURCE_POOL_IDLE_TTL",
        "DATASOURCE_MAX_IDLE_POOLS",
        "DATASOURCE_QUERY_TIMEOUT",
    ):
        monkeypatch.delenv(name, raising=False)

    settings = config.datasource_pool_settings()

    assert settings == {
        "pool_size": 2,
        "max_overflow": 3,
        "pool_timeout": 10,
        "pool_recycle": 1800,
        "idle_ttl": 900,
        "max_idle_pools": 20,
        "query_timeout": 30,
    }
    assert config.BaseConfig.DATASOURCE_POOL_SIZE == 2
    assert config.BaseConfig.DATASOURCE_MAX_OVERFLOW == 3
    assert config.BaseConfig.DATASOURCE_POOL_TIMEOUT == 10
    assert config.BaseConfig.DATASOURCE_POOL_RECYCLE == 1800
    assert config.BaseConfig.DATASOURCE_POOL_IDLE_TTL == 900
    assert config.BaseConfig.DATASOURCE_MAX_IDLE_POOLS == 20
    assert config.BaseConfig.DATASOURCE_QUERY_TIMEOUT == 30


def test_pool_limits_reject_unsafe_values(monkeypatch):
    monkeypatch.setenv("DATASOURCE_POOL_SIZE", "100")

    with pytest.raises(ValueError, match="DATASOURCE_POOL_SIZE"):
        config.datasource_pool_settings()


def test_datasource_override_is_limited_to_allowlisted_bounded_values():
    settings = config.datasource_pool_settings(
        {"pool_size": 4, "max_overflow": 5}
    )

    assert settings["pool_size"] == 4
    assert settings["max_overflow"] == 5

    with pytest.raises(ValueError, match="pool_size"):
        config.datasource_pool_settings({"pool_size": 11})

    with pytest.raises(ValueError, match="Unsupported"):
        config.datasource_pool_settings({"pool_timeout": 20})
