"""S4.7 / package 2 (K5 cleanup): the DB Shell unlock password is read by `modules.core.config.db_shell_password()` on every call,
without a cache and without a default; the route behaves exactly as before."""
import pytest

from InvestmentManager.routes import dbshell
from tests.investmentmanager.conftest import CRM_MASTER
from modules.core import config

SECRET = 'cfg-secret-value'


def test_config_function_reads_the_environment_on_every_call(monkeypatch):
    monkeypatch.delenv('DB_SHELL_PASSWORD', raising=False)
    assert config.db_shell_password() == ''
    monkeypatch.setenv('DB_SHELL_PASSWORD', 'one')
    assert config.db_shell_password() == 'one'
    monkeypatch.setenv('DB_SHELL_PASSWORD', 'two')
    assert config.db_shell_password() == 'two'
    monkeypatch.setenv('DB_SHELL_PASSWORD', '')
    assert config.db_shell_password() == ''


def test_route_helper_delegates_to_the_config_function(monkeypatch):
    monkeypatch.setenv('DB_SHELL_PASSWORD', 'x1')
    assert dbshell._get_db_shell_password() == 'x1'
    monkeypatch.setenv('DB_SHELL_PASSWORD', 'x2')
    assert dbshell._get_db_shell_password() == 'x2'
    monkeypatch.delenv('DB_SHELL_PASSWORD')
    assert dbshell._get_db_shell_password() == ''


def test_dbshell_module_no_longer_reads_the_environment_directly():
    source = open(dbshell.__file__, encoding='utf-8-sig').read()
    assert 'os.environ' not in source and 'os.getenv' not in source


@pytest.mark.crm_session_guard
def test_unlock_follows_the_environment_between_calls(app, crm_env, crm_login, monkeypatch):
    client = crm_login(app, CRM_MASTER)
    monkeypatch.setenv('DB_SHELL_PASSWORD', SECRET)
    assert client.post('/crm/dbshell/unlock', json={'password': SECRET}).status_code == 200
    assert client.post('/crm/dbshell/unlock', json={'password': 'wrong'}).status_code == 401
    monkeypatch.setenv('DB_SHELL_PASSWORD', 'changed-' + SECRET)
    assert client.post('/crm/dbshell/unlock', json={'password': SECRET}).status_code == 401
    assert client.post('/crm/dbshell/unlock', json={'password': 'changed-' + SECRET}).status_code == 200
    monkeypatch.setenv('DB_SHELL_PASSWORD', '')
    assert client.post('/crm/dbshell/unlock', json={'password': ''}).status_code == 503
    monkeypatch.delenv('DB_SHELL_PASSWORD')
    assert client.post('/crm/dbshell/unlock', json={'password': SECRET}).status_code == 503
