"""Teste scope cont pe GET /v1/audit/export (US-003, PRD 3.2)."""

from __future__ import annotations

import csv
import io
import json
import os
import tempfile

import pytest
from fastapi.testclient import TestClient


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


def _client():
    from app.main import app
    return TestClient(app)


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": "s"}, "prezentari": [prez]}


def _csv_vins(content: bytes) -> list[str]:
    reader = csv.DictReader(io.StringIO(content.decode("utf-8")))
    return [r["vin"] for r in reader if r.get("vin")]


def test_export_doar_contul_cheii(env):
    """Exportul CSV contine doar randurile contului asociat cheii."""
    with _client() as c:
        from app.auth import create_api_key
        from app.db import get_connection
        conn = get_connection()
        try:
            # tier='pro' ca sa treaca gate-ul API (T4 PRD 5.17); testul masoara scoping, nu planuri.
            conn.execute("INSERT INTO accounts (id, name, tier) VALUES (2, 'al-doilea', 'pro')")
            k1 = create_api_key(conn, 1)
            k2 = create_api_key(conn, 2)
        finally:
            conn.close()

        c.post("/v1/prezentari", json=_body(), headers={"X-API-Key": k1})
        c.post("/v1/prezentari", json=_body(vin="WVWZZZ1KZAW000456"), headers={"X-API-Key": k2})

        # Marcheaza ca sent pentru ca audit/export default e status=sent
        conn2 = get_connection()
        try:
            conn2.execute("UPDATE submissions SET status='sent'")
        finally:
            conn2.close()

        resp1 = c.get("/v1/audit/export", headers={"X-API-Key": k1})
        assert resp1.status_code == 200
        vins1 = _csv_vins(resp1.content)
        assert "WVWZZZ1KZAW000123" in vins1
        assert "WVWZZZ1KZAW000456" not in vins1

        resp2 = c.get("/v1/audit/export", headers={"X-API-Key": k2})
        vins2 = _csv_vins(resp2.content)
        assert "WVWZZZ1KZAW000456" in vins2
        assert "WVWZZZ1KZAW000123" not in vins2


def test_export_legacy_null_pentru_cont_1(env):
    """Randuri cu account_id=NULL apartin contului 1 in exportul de audit; contul 2 nu le vede."""
    with _client() as c:
        from app.auth import create_api_key
        from app.db import get_connection
        conn = get_connection()
        try:
            conn.execute("INSERT INTO accounts (id, name) VALUES (2, 'al-doilea')")
            k1 = create_api_key(conn, 1)
            k2 = create_api_key(conn, 2)
            payload = json.dumps({"vin": "LEGACYVIN12345678", "prestatii": []})
            conn.execute(
                "INSERT INTO submissions (idempotency_key, account_id, status, payload_json) "
                "VALUES ('legacy_audit_key', NULL, 'sent', ?)", (payload,)
            )
        finally:
            conn.close()

        resp1 = c.get("/v1/audit/export", headers={"X-API-Key": k1})
        vins1 = _csv_vins(resp1.content)
        assert "LEGACYVIN12345678" in vins1

        resp2 = c.get("/v1/audit/export", headers={"X-API-Key": k2})
        vins2 = _csv_vins(resp2.content)
        assert "LEGACYVIN12345678" not in vins2


def test_export_status_all_tot_scoped(env):
    """status=all ramane scoped pe cont (nu exporta global)."""
    with _client() as c:
        from app.auth import create_api_key
        from app.db import get_connection
        conn = get_connection()
        try:
            conn.execute("INSERT INTO accounts (id, name) VALUES (2, 'al-doilea')")
            k1 = create_api_key(conn, 1)
            k2 = create_api_key(conn, 2)
        finally:
            conn.close()

        c.post("/v1/prezentari", json=_body(), headers={"X-API-Key": k1})
        c.post("/v1/prezentari", json=_body(vin="WVWZZZ1KZAW000456"), headers={"X-API-Key": k2})

        resp1 = c.get("/v1/audit/export?status=all", headers={"X-API-Key": k1})
        vins1 = _csv_vins(resp1.content)
        assert "WVWZZZ1KZAW000123" in vins1
        assert "WVWZZZ1KZAW000456" not in vins1
