"""Teste C6: /_fragments/mapari scoped pe sesiune (task #7 fix leak cross-account).

TDD: testele confirma mai intai ca leak-ul exista (RED), apoi fix-ul il inchide (GREEN).
"""

from __future__ import annotations

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, "mapari.db"))
    from app.config import get_settings
    get_settings.cache_clear()
    from app.main import app
    with TestClient(app, follow_redirects=False) as c:
        from app.db import get_connection
        conn = get_connection()
        from app.accounts import create_account
        acct_a = create_account(conn, "Cont A Mapari")
        acct_b = create_account(conn, "Cont B Mapari")
        yield c, conn, acct_a, acct_b
        conn.close()
    get_settings.cache_clear()


def _insert_needs_mapping(conn, account_id, cod_op):
    payload = json.dumps({"vin": "VIN001", "nr_inmatriculare": "B01TST",
                          "data_prestatie": "2026-06-01", "odometru_final": "1000",
                          "prestatii": [{"cod_op_service": cod_op, "denumire": cod_op}]})
    conn.execute(
        "INSERT INTO submissions (idempotency_key, account_id, status, payload_json) "
        "VALUES (?, ?, 'needs_mapping', ?)",
        (f"key_{account_id}_{cod_op}", account_id, payload),
    )


def test_fragment_mapari_scoped_pe_cont(env, monkeypatch):
    """/_fragments/mapari arata doar op-urile contului din sesiune, nu ale altuia."""
    client, conn, acct_a, acct_b = env
    _insert_needs_mapping(conn, acct_a, "OP-DOAR-A")
    _insert_needs_mapping(conn, acct_b, "OP-DOAR-B")

    import app.web.routes as routes
    monkeypatch.setattr("app.web.routes.require_login", lambda r: acct_a)
    r = client.get("/_fragments/mapari")
    assert r.status_code == 200
    assert "OP-DOAR-A" in r.text
    assert "OP-DOAR-B" not in r.text

    monkeypatch.setattr("app.web.routes.require_login", lambda r: acct_b)
    r = client.get("/_fragments/mapari")
    assert r.status_code == 200
    assert "OP-DOAR-B" in r.text
    assert "OP-DOAR-A" not in r.text


def test_fragment_mapari_nelogat_redirect(monkeypatch):
    """web_auth_required=True + fara sesiune -> 303 /login."""
    tmp = tempfile.mkdtemp()
    monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "mapari_auth.db"))
    monkeypatch.setenv("AUTOPASS_WEB_AUTH_REQUIRED", "true")
    from app.config import get_settings
    get_settings.cache_clear()
    from app.main import app
    with TestClient(app, follow_redirects=False) as c:
        r = c.get("/_fragments/mapari")
        assert r.status_code == 303
        assert "/login" in r.headers.get("location", "")
    get_settings.cache_clear()
