"""Regression: DB connection pool size must be configurable via env var.

Port of crystallise-master commit 1ced6ab. Pre-fix, the PostgreSQL
connection pool size was hardcoded to maxconn=5 in
`DatabaseBackend.__init__` and exhausted within ~14 seconds of a backend
cold-start under a normal multi-tab page-load burst (visible as 500s
with `psycopg2.pool.PoolError: connection pool exhausted`).

After fix: `get_backend()` reads `Settings.db_pool_size` (env var
`CRYSTALLISE_DB_POOL_SIZE`, default 20) and propagates it.
"""
from __future__ import annotations

import pytest


def test_settings_exposes_db_pool_size_with_default_20(monkeypatch):
    """The Settings type must expose db_pool_size with a sane default."""
    monkeypatch.delenv("CRYSTALLISE_DB_POOL_SIZE", raising=False)
    from crystallise.config.settings import Settings

    s = Settings()
    assert s.db_pool_size == 20, (
        "Default pool size should be 20 (raised from the pre-incident value of 5 "
        "which exhausted under normal page-load bursts on crystallise-master prod)."
    )


def test_settings_db_pool_size_honours_env_var(monkeypatch):
    monkeypatch.setenv("CRYSTALLISE_DB_POOL_SIZE", "42")
    from crystallise.config.settings import Settings

    s = Settings()
    assert s.db_pool_size == 42


@pytest.mark.parametrize("env_value, expected", [("8", 8), ("100", 100)])
def test_get_backend_propagates_pool_size_to_databasebackend(monkeypatch, env_value, expected):
    """get_backend() must read Settings.db_pool_size and pass it through.

    The session-wide test fixture may monkeypatch `backend_mod.get_backend`.
    To exercise the real implementation, reload the module after setting the
    env var so the patched lambda is replaced with the actual function.
    """
    monkeypatch.setenv("CRYSTALLISE_DB_POOL_SIZE", env_value)
    monkeypatch.setenv("CRYSTALLISE_DATABASE_URL", "")  # force SQLite

    import importlib
    import crystallise.db.backend as backend_mod
    real_module = importlib.reload(backend_mod)

    real_module.reset_backend()
    try:
        b = real_module.get_backend()
        assert b.pool_size == expected, (
            f"get_backend() returned pool_size={b.pool_size}, expected {expected}. "
            "The env var must reach DatabaseBackend via Settings."
        )
    finally:
        real_module.reset_backend()
