"""Teste US-007 (PRD 5.6): gard de redactare PII/parole in jurnal (L.142/GDPR)."""

from __future__ import annotations

import os
import tempfile

import pytest


@pytest.fixture()
def env(monkeypatch):
    tmp = tempfile.mkdtemp()
    monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "red.db"))
    monkeypatch.setenv("AUTOPASS_LOG_DIR", os.path.join(tmp, "logs"))
    from app.config import get_settings
    get_settings.cache_clear()
    from app.db import init_db
    init_db()
    yield tmp
    get_settings.cache_clear()


def _all_events_text():
    from app.db import get_connection
    conn = get_connection()
    try:
        rows = conn.execute("SELECT mesaj, context_json FROM app_events").fetchall()
    finally:
        conn.close()
    return "\n".join((r["mesaj"] or "") + " " + (r["context_json"] or "") for r in rows)


def test_vin_logat_partial():
    from app.security import vin_partial
    assert vin_partial("WVWZZZ1KZAW000123") == "WVW…0123"
    assert "WVWZZZ1KZAW000123" not in vin_partial("WVWZZZ1KZAW000123")
    assert vin_partial("") == ""
    assert vin_partial("AB") == "…"


def test_parola_niciodata_in_app_events(env):
    from app import observ
    observ.log_event(
        "test_creds",
        account_id=1,
        mesaj='login cu password="parolaABC" si token=eyJsecret',
        context={"rar_credentials": {"email": "a@b.ro", "password": "parolaABC"},
                 "password": "parolaABC", "token": "eyJsecret"},
    )
    blob = _all_events_text()
    assert "parolaABC" not in blob
    assert "eyJsecret" not in blob
    assert "***REDACTED***" in blob


def test_payload_integral_nu_se_logheaza(env):
    """Un VIN integral pus in context se reduce la partial (nu se logheaza intreg)."""
    from app import observ
    observ.log_event("test_vin", context={"vin": "WVWZZZ1KZAW000123", "nr_inmatriculare": "B123ABC"})
    blob = _all_events_text()
    assert "WVWZZZ1KZAW000123" not in blob
    assert "0123" in blob  # partial pastrat


def test_fuzz_chei_sensibile_mascate(env):
    """Orice cheie sensibila in context -> mascata, oricat de adanc."""
    from app import observ
    observ.log_event("fuzz", context={
        "nivel1": {"secret": "AAA", "pwd": "BBB", "ok": "vizibil"},
        "lista": [{"jwt": "CCC"}, {"apikey": "DDD"}],
        "authorization": "Bearer eyJxyz",
    })
    blob = _all_events_text()
    for leak in ("AAA", "BBB", "CCC", "DDD", "eyJxyz"):
        assert leak not in blob, f"scurgere: {leak}"
    assert "vizibil" in blob  # campurile benigne raman
