"""Teste US-005 (PRD 3.5): listare + editare/stergere mapari operatii salvate.

Scoped pe cont (fara leak cross-account). Editarea respinge cod inexistent in
nomenclator si re-rezolva submission-urile blocate pe acel cod_op_service.
"""

from __future__ import annotations

import os
import re
import tempfile

import pytest
from starlette.testclient import TestClient


def _create_account_user(email: str, name: str = "Service", password: str = "parolasecreta10"):
    from app.accounts import create_account
    from app.users import create_user
    from app.db import get_connection

    conn = get_connection()
    try:
        acct_id = create_account(conn, name, active=True)
        create_user(conn, acct_id, email, password)
        return acct_id
    finally:
        conn.close()


def _login(client, email: str, password: str = "parolasecreta10") -> None:
    resp = client.get("/login")
    m = re.search(r'name="csrf_token"\s+value="([^"]+)"', resp.text) or \
        re.search(r'value="([^"]+)"\s+name="csrf_token"', resp.text)
    assert m
    resp = client.post("/login", data={"email": email, "parola": password, "csrf_token": m.group(1)})
    assert resp.status_code == 303


def _csrf(client) -> str:
    resp = client.get("/?tab=mapari")
    m = re.search(r'name="csrf_token"\s+value="([^"]+)"', resp.text) or \
        re.search(r'value="([^"]+)"\s+name="csrf_token"', resp.text)
    assert m, "csrf_token negasit"
    return m.group(1)


def _seed_nomenclator(cod: str, nume: str = "Test prestatie") -> None:
    from app.db import get_connection
    conn = get_connection()
    try:
        conn.execute(
            "INSERT OR REPLACE INTO nomenclator_rar (cod_prestatie, nume_prestatie) VALUES (?, ?)",
            (cod, nume),
        )
        conn.commit()
    finally:
        conn.close()


def _seed_op_mapping(acct: int, op: str, cod: str, auto_send: int = 1) -> None:
    from app.db import get_connection
    conn = get_connection()
    try:
        conn.execute(
            "INSERT INTO operations_mapping (account_id, cod_op_service, cod_prestatie, auto_send) "
            "VALUES (?, ?, ?, ?)",
            (acct, op, cod, auto_send),
        )
        conn.commit()
    finally:
        conn.close()


def _seed_needs_mapping(acct: int, op: str) -> int:
    """Submission needs_mapping pe canal API (batch_id NULL) cu o operatie nemapata."""
    from app.db import get_connection
    import json
    conn = get_connection()
    try:
        cur = conn.execute(
            "INSERT INTO submissions (idempotency_key, account_id, status, payload_json) "
            "VALUES (?, ?, 'needs_mapping', ?)",
            (
                f"k-{op}-{os.urandom(4).hex()}",
                acct,
                json.dumps({
                    "vin": "WVWZZZ1JZXW000111",
                    "nr_inmatriculare": "B11AAA",
                    "data_prestatie": "2026-06-18",
                    "odometru_final": "12345",
                    "prestatii": [{"cod_op_service": op, "denumire": "ceva"}],
                }),
            ),
        )
        conn.commit()
        return cur.lastrowid
    finally:
        conn.close()


def _status_of(sid: int) -> str:
    from app.db import get_connection
    conn = get_connection()
    try:
        return conn.execute("SELECT status FROM submissions WHERE id=?", (sid,)).fetchone()["status"]
    finally:
        conn.close()


@pytest.fixture()
def client(monkeypatch):
    tmp = tempfile.mkdtemp()
    monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "mapari_salvate.db"))
    monkeypatch.setenv("AUTOPASS_WEB_AUTH_REQUIRED", "true")
    from app.config import get_settings
    get_settings.cache_clear()
    from app.web import ratelimit
    ratelimit._hits.clear()
    from app.main import app
    with TestClient(app, follow_redirects=False) as c:
        yield c
    ratelimit._hits.clear()
    get_settings.cache_clear()


def test_lista_mapari_salvate(client):
    """Listarea intoarce randurile operations_mapping ale contului cu nume_prestatie."""
    acct = _create_account_user("lista@test.com")
    _seed_nomenclator("R-FRANE", "Reparatie frane")
    _seed_op_mapping(acct, "OP-100", "R-FRANE")

    from app.db import get_connection
    from app.web.routes import _load_saved_op_mappings
    conn = get_connection()
    try:
        rows = _load_saved_op_mappings(conn, acct)
    finally:
        conn.close()

    assert len(rows) == 1
    assert rows[0]["cod_op_service"] == "OP-100"
    assert rows[0]["cod_prestatie"] == "R-FRANE"
    assert rows[0]["nume_prestatie"] == "Reparatie frane"
    assert rows[0]["auto_send"] is True


def test_editeaza_mapare_salvata(client):
    """POST schimba cod_prestatie; respinge cod inexistent; scoped pe cont."""
    acct = _create_account_user("edit@test.com")
    _seed_nomenclator("R-FRANE", "Reparatie frane")
    _seed_nomenclator("R-MOTOR", "Reparatie motor")
    _seed_op_mapping(acct, "OP-100", "R-FRANE")
    _login(client, "edit@test.com")
    csrf = _csrf(client)

    # Cod inexistent -> respins
    resp = client.post("/mapari/salvate", data={
        "cod_op_service": "OP-100", "cod_prestatie": "NU-EXISTA", "csrf_token": csrf,
    })
    assert resp.status_code == 200
    assert "necunoscut" in resp.text.lower()

    # Cod valid -> actualizat
    resp = client.post("/mapari/salvate", data={
        "cod_op_service": "OP-100", "cod_prestatie": "R-MOTOR", "auto_send": "true", "csrf_token": csrf,
    })
    assert resp.status_code == 200

    from app.db import get_connection
    conn = get_connection()
    try:
        row = conn.execute(
            "SELECT cod_prestatie FROM operations_mapping WHERE account_id=? AND cod_op_service=?",
            (acct, "OP-100"),
        ).fetchone()
    finally:
        conn.close()
    assert row["cod_prestatie"] == "R-MOTOR"


def test_editeaza_deblocheaza_submissions(client):
    """La editarea unui cod, submission-urile needs_mapping pe acel op se deblocheaza."""
    acct = _create_account_user("debloc@test.com")
    _seed_nomenclator("R-FRANE", "Reparatie frane")
    sid = _seed_needs_mapping(acct, "OP-200")
    assert _status_of(sid) == "needs_mapping"

    _login(client, "debloc@test.com")
    csrf = _csrf(client)
    resp = client.post("/mapari/salvate", data={
        "cod_op_service": "OP-200", "cod_prestatie": "R-FRANE", "auto_send": "true", "csrf_token": csrf,
    })
    assert resp.status_code == 200
    assert _status_of(sid) != "needs_mapping"  # deblocat (queued sau needs_data)


def test_sterge_mapare_salvata_scoped(client):
    """DELETE scoped pe cont: maparea altui cont ramane neatinsa."""
    acct1 = _create_account_user("st1@test.com", name="Cont1")
    acct2 = _create_account_user("st2@test.com", name="Cont2")
    _seed_nomenclator("R-FRANE")
    _seed_op_mapping(acct1, "OP-X", "R-FRANE")
    _seed_op_mapping(acct2, "OP-X", "R-FRANE")

    _login(client, "st1@test.com")
    csrf = _csrf(client)
    resp = client.post("/mapari/salvate/sterge", data={"cod_op_service": "OP-X", "csrf_token": csrf})
    assert resp.status_code == 200

    from app.db import get_connection
    conn = get_connection()
    try:
        r1 = conn.execute("SELECT 1 FROM operations_mapping WHERE account_id=? AND cod_op_service='OP-X'", (acct1,)).fetchone()
        r2 = conn.execute("SELECT 1 FROM operations_mapping WHERE account_id=? AND cod_op_service='OP-X'", (acct2,)).fetchone()
    finally:
        conn.close()
    assert r1 is None, "maparea contului propriu trebuia stearsa"
    assert r2 is not None, "maparea altui cont NU trebuia atinsa (leak)"
