"""Security tests for the DB Shell unlock endpoint
(InvestmentManager/routes/dashboard.py::dbshell_unlock).

Context: DB_SHELL_PASSWORD used to be a hardcoded 'void' constant in
production code. It is now read from the DB_SHELL_PASSWORD environment
variable with no fallback/default, so DB Shell unlock fails closed whenever
that variable is unset or empty. These tests never touch the real .env —
the value is set/unset per test via monkeypatch.setenv/delenv, and the
`client` fixture builds the app via the real create_app() without loading
dotenv (see tests/conftest.py).

Endpoint: POST /crm/dbshell/unlock
Gates, in order: CRM session (before_request in InvestmentManager/__init__.py)
-> _is_master_user() -> DB_SHELL_PASSWORD configured -> password match.
"""
import pytest


UNLOCK_URL = "/crm/dbshell/unlock"


def _login(client, *, master):
    with client.session_transaction() as sess:
        sess["user_id"] = 1
        sess["access_level"] = "master" if master else "agent"


class TestDbShellUnlockFailsClosedWithoutConfiguredPassword:
    def test_env_var_unset_denies_access_even_with_master(self, client, monkeypatch):
        monkeypatch.delenv("DB_SHELL_PASSWORD", raising=False)
        _login(client, master=True)

        resp = client.post(UNLOCK_URL, json={"password": "anything"})

        assert resp.status_code == 503
        assert resp.get_json()["success"] is False

    def test_env_var_empty_string_denies_access_even_with_master(self, client, monkeypatch):
        monkeypatch.setenv("DB_SHELL_PASSWORD", "")
        _login(client, master=True)

        resp = client.post(UNLOCK_URL, json={"password": ""})

        assert resp.status_code == 503
        assert resp.get_json()["success"] is False

    def test_no_hardcoded_void_password_works_when_unset(self, client, monkeypatch):
        # The old hardcoded default was the literal string 'void'. Confirm
        # that no longer unlocks anything even though env is unset.
        monkeypatch.delenv("DB_SHELL_PASSWORD", raising=False)
        _login(client, master=True)

        resp = client.post(UNLOCK_URL, json={"password": "void"})

        assert resp.status_code == 503
        assert resp.get_json()["success"] is False


class TestDbShellUnlockWithConfiguredPassword:
    def test_wrong_password_denies_access(self, client, monkeypatch):
        monkeypatch.setenv("DB_SHELL_PASSWORD", "s3cr3t-value")
        _login(client, master=True)

        resp = client.post(UNLOCK_URL, json={"password": "wrong-value"})

        assert resp.status_code == 401
        body = resp.get_json()
        assert body["success"] is False
        assert "Nieprawidłowe hasło" in body["error"]

    def test_correct_password_with_master_unlocks(self, client, monkeypatch):
        monkeypatch.setenv("DB_SHELL_PASSWORD", "s3cr3t-value")
        _login(client, master=True)

        resp = client.post(UNLOCK_URL, json={"password": "s3cr3t-value"})

        assert resp.status_code == 200
        assert resp.get_json() == {"success": True}

        with client.session_transaction() as sess:
            assert "db_shell_unlocked_at" in sess

    def test_correct_password_without_master_is_denied(self, client, monkeypatch):
        monkeypatch.setenv("DB_SHELL_PASSWORD", "s3cr3t-value")
        _login(client, master=False)

        resp = client.post(UNLOCK_URL, json={"password": "s3cr3t-value"})

        assert resp.status_code == 403
        assert resp.get_json()["error"] == "Brak uprawnień."

        with client.session_transaction() as sess:
            assert "db_shell_unlocked_at" not in sess

    def test_master_check_happens_before_password_check(self, client, monkeypatch):
        # Even a correct password must not leak unlock state for a
        # non-master session: permission is checked first.
        monkeypatch.delenv("DB_SHELL_PASSWORD", raising=False)
        _login(client, master=False)

        resp = client.post(UNLOCK_URL, json={"password": "void"})

        assert resp.status_code == 403


class TestDbShellUnlockRequiresCrmSession:
    def test_no_session_at_all_is_rejected_by_crm_auth_gate(self, client, monkeypatch):
        monkeypatch.setenv("DB_SHELL_PASSWORD", "s3cr3t-value")

        resp = client.post(UNLOCK_URL, json={"password": "s3cr3t-value"})

        assert resp.status_code == 403
        assert resp.get_json()["code"] == "auth_required"
