"""Teste US-004 (PRD 5.6): audit cerere API per cont in jurnal."""

from __future__ import annotations

import os
import tempfile

import pytest
from fastapi.testclient import TestClient


@pytest.fixture()
def client(monkeypatch):
    tmp = tempfile.mkdtemp()
    monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "audit.db"))
    monkeypatch.setenv("AUTOPASS_LOG_DIR", os.path.join(tmp, "logs"))
    monkeypatch.setenv("AUTOPASS_REQUIRE_API_KEY", "false")
    from app.config import get_settings
    get_settings.cache_clear()
    from app.main import app
    with TestClient(app) as c:
        yield c
    get_settings.cache_clear()


def _body(**over):
    prez = {"vin": "WVWZZZ1KZAW000123", "nr_inmatriculare": "B999TST",
            "data_prestatie": "2026-06-15", "odometru_final": "123456",
            "prestatii": [{"cod_prestatie": "OE-1"}]}
    prez.update(over)
    return {"rar_credentials": {"email": "x@y.ro", "password": "secretaPP"}, "prezentari": [prez]}


def _events(tip):
    from app.db import get_connection
    conn = get_connection()
    try:
        return conn.execute("SELECT * FROM app_events WHERE tip=?", (tip,)).fetchall()
    finally:
        conn.close()


def test_post_prezentari_logheaza_eveniment_cont(client):
    r = client.post("/v1/prezentari", json=_body())
    assert r.status_code == 200
    rows = _events("api_prezentari")
    assert len(rows) == 1
    assert rows[0]["account_id"] == 1


def test_eveniment_contine_status_si_count_fara_pii(client):
    client.post("/v1/prezentari", json=_body())
    rows = _events("api_prezentari")
    ctx = rows[0]["context_json"]
    assert "distributie" in ctx
    assert "queued" in ctx
    assert "count" in ctx
    # NICIUN PII integral (parola / VIN integral)
    assert "secretaPP" not in ctx
    assert "WVWZZZ1KZAW000123" not in ctx


def test_401_logat_ca_auth_esuat(client):
    # cheie prezenta dar invalida -> 401 (indiferent de flag)
    r = client.post("/v1/prezentari", json=_body(), headers={"X-API-Key": "rfak_invalidakey123"})
    assert r.status_code == 401
    rows = _events("api_auth_esuat")
    assert len(rows) == 1
    ctx = rows[0]["context_json"]
    # prefix cheie, NU cheia intreaga
    assert "rfak_inv" in ctx
    assert "rfak_invalidakey123" not in ctx
