"""Teste US-005 (PRD 3.3): scoping dashboard pe sesiune (2 conturi, citiri).

Comportamental (C6): nu grep, ci verificare reala cu 2 conturi + date distincte.
"""

from __future__ import annotations

import json
import os
import tempfile

import pytest
from fastapi.testclient import TestClient


@pytest.fixture()
def env(monkeypatch):
    """DB temporar + app principal."""
    tmp = tempfile.mkdtemp()
    monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "t.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()
        yield c, conn
        conn.close()
    get_settings.cache_clear()


def _make_account(conn, name, active=True):
    from app.accounts import create_account
    return create_account(conn, name, active=active)


def _insert_submission(conn, account_id, vin="WVWZZZ1KZAW000001", status="queued"):
    key = f"key_{account_id}_{vin}_{status}"
    payload = json.dumps({"vin": vin, "nr_inmatriculare": "B001TST",
                          "data_prestatie": "2026-06-01", "odometru_final": "100",
                          "prestatii": [{"cod_prestatie": "OE-1"}]})
    conn.execute(
        "INSERT INTO submissions (idempotency_key, account_id, status, payload_json) "
        "VALUES (?, ?, ?, ?)",
        (key, account_id, status, payload),
    )


def test_counts_doar_contul_sesiunii(env, monkeypatch):
    """_status_counts scoped: contul A vede doar ale lui, nu ale lui B."""
    client, conn = env
    acct_a = _make_account(conn, "Cont A")
    acct_b = _make_account(conn, "Cont B")
    _insert_submission(conn, acct_a, vin="AAAAAAAAAAAA00001")
    _insert_submission(conn, acct_a, vin="AAAAAAAAAAAA00002")
    _insert_submission(conn, acct_b, vin="BBBBBBBBBBBB00001")

    # Contul A vede 2 submissions
    monkeypatch.setattr("app.web.routes.require_login", lambda r: acct_a)
    r = client.get("/")
    assert r.status_code == 200
    assert "2" in r.text  # 2 queued pentru A

    # Contul B vede 1 submission
    monkeypatch.setattr("app.web.routes.require_login", lambda r: acct_b)
    r = client.get("/")
    assert r.status_code == 200


def test_submissions_fragment_scoped(env, monkeypatch):
    """/_fragments/submissions arata doar submission-urile contului din sesiune.

    VIN-ul e in payload_json (nu in HTML), asa ca testam dupa r.id din template.
    """
    client, conn = env
    acct_a = _make_account(conn, "Cont A2")
    acct_b = _make_account(conn, "Cont B2")
    _insert_submission(conn, acct_a, vin="AAONLY000000000VIN")
    _insert_submission(conn, acct_b, vin="BBONLY000000000VIN")
    sub_a = conn.execute("SELECT id FROM submissions WHERE account_id=?", (acct_a,)).fetchone()["id"]
    sub_b = conn.execute("SELECT id FROM submissions WHERE account_id=?", (acct_b,)).fetchone()["id"]

    monkeypatch.setattr("app.web.routes.require_login", lambda r: acct_a)
    r = client.get("/_fragments/submissions")
    assert r.status_code == 200
    assert f'id="trimitere-row-{sub_a}"' in r.text
    assert f'id="trimitere-row-{sub_b}"' not in r.text

    monkeypatch.setattr("app.web.routes.require_login", lambda r: acct_b)
    r = client.get("/_fragments/submissions")
    assert r.status_code == 200
    assert f'id="trimitere-row-{sub_b}"' in r.text
    assert f'id="trimitere-row-{sub_a}"' not in r.text


def test_nelogat_landing(monkeypatch):
    """web_auth_required=True + fara sesiune -> landing comercial (200) la /.

    "/" e suprafata publica: vizitatorul vede landing-ul cu formularele de
    inregistrare/autentificare (post la /signup, /login). Rutele protejate
    (fragmente, POST-uri) raman redirect /login.
    """
    tmp = tempfile.mkdtemp()
    monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "t_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("/")
        assert r.status_code == 200
        assert 'action="/signup"' in r.text
        assert 'action="/login"' in r.text
        # ruta protejata fara sesiune -> tot redirect /login
        r2 = c.get("/_fragments/submissions")
        assert r2.status_code == 303
        assert "/login" in r2.headers.get("location", "")
    get_settings.cache_clear()


def test_banner_cont_in_asteptare(env, monkeypatch):
    """Contul cu active=0 vede banner 'in asteptare'; contul activ nu il vede."""
    client, conn = env
    acct_inactiv = _make_account(conn, "Cont Inactiv", active=False)
    acct_activ = _make_account(conn, "Cont Activ", active=True)

    monkeypatch.setattr("app.web.routes.require_login", lambda r: acct_inactiv)
    r = client.get("/_fragments/banner")
    assert r.status_code == 200
    assert "asteptare" in r.text.lower() or "activare" in r.text.lower()

    monkeypatch.setattr("app.web.routes.require_login", lambda r: acct_activ)
    r = client.get("/_fragments/banner")
    assert r.status_code == 200
    assert "asteptare" not in r.text.lower() or "activare" not in r.text.lower()
