"""Teste POST /trimitere/{id}/mapeaza — US-001 auto_send ignorat.

Dupa US-001: auto_send nu mai tine randul in needs_mapping; un cod valid mapat
-> queued direct, indiferent de valoarea auto_send din form sau din mapping_meta.
"""

from __future__ import annotations

import json
import os
import tempfile

import pytest
from starlette.testclient import TestClient


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


@pytest.fixture()
def conn(client):
    """Conexiune directa la DB-ul deja initializat de client."""
    from app.db import get_connection
    c = get_connection()
    yield c
    c.close()


def _add_nomenclator(conn, cod="OE-1"):
    conn.execute(
        "INSERT OR IGNORE INTO nomenclator_rar (cod_prestatie, nume_prestatie) VALUES (?, ?)",
        (cod, f"Operatie {cod}"),
    )
    conn.commit()


def _insert_needs_mapping(conn, cod_op="ITP-CHECK"):
    payload = {
        "vin": "WVWZZZ1KZAW000123", "nr_inmatriculare": "B1",
        "data_prestatie": "2026-06-15", "odometru_final": "123456",
        "prestatii": [{"cod_op_service": cod_op, "denumire": "Inspectie tehnica"}],
    }
    cur = conn.execute(
        "INSERT INTO submissions (idempotency_key, account_id, status, payload_json) "
        "VALUES (?, ?, ?, ?)",
        (f"k-{os.urandom(4).hex()}", 1, "needs_mapping", json.dumps(payload)),
    )
    conn.commit()
    return int(cur.lastrowid)


def test_mapeaza_inline_auto_send_zero_in_form_tot_queued(client, conn):
    """POST /trimitere/{id}/mapeaza cu auto_send=0 explicit in form -> queued dupa US-001.

    Vechi comportament: reresolve_account vedea auto_send=0 -> review_manual -> needs_mapping.
    Nou comportament: has_no_auto_send returneaza False -> queued direct.
    """
    _add_nomenclator(conn)
    sid = _insert_needs_mapping(conn)

    r = client.post(
        f"/trimitere/{sid}/mapeaza",
        data={
            "cod_op_service": "ITP-CHECK",
            "cod_prestatie": "OE-1",
            "auto_send": "0",
        },
    )
    assert r.status_code == 200
    row = conn.execute("SELECT status FROM submissions WHERE id=?", (sid,)).fetchone()
    assert row["status"] == "queued", (
        f"auto_send=0 in form nu trebuie sa tina randul dupa US-001, got {row['status']}"
    )


def test_mapeaza_inline_fara_auto_send_form_tot_queued(client, conn):
    """POST /trimitere/{id}/mapeaza fara auto_send in form -> queued dupa US-001."""
    _add_nomenclator(conn)
    sid = _insert_needs_mapping(conn)

    r = client.post(
        f"/trimitere/{sid}/mapeaza",
        data={"cod_op_service": "ITP-CHECK", "cod_prestatie": "OE-1"},
    )
    assert r.status_code == 200
    row = conn.execute("SELECT status FROM submissions WHERE id=?", (sid,)).fetchone()
    assert row["status"] == "queued", (
        f"fara auto_send -> asteptat queued, got {row['status']}"
    )


def test_mapeaza_inline_raspuns_fara_mesaj_auto_send(client, conn):
    """Raspunsul la mapare nu contine text despre auto-send oprit."""
    _add_nomenclator(conn)
    sid = _insert_needs_mapping(conn)

    r = client.post(
        f"/trimitere/{sid}/mapeaza",
        data={"cod_op_service": "ITP-CHECK", "cod_prestatie": "OE-1", "auto_send": "0"},
    )
    assert r.status_code == 200
    body = r.text.lower()
    assert "auto-send oprit" not in body, "raspunsul nu trebuie sa contina card 'auto-send oprit'"
    assert "review manual inainte de trimitere" not in body, (
        "raspunsul nu trebuie sa contina mesajul vechi de auto_send"
    )


def test_mapeaza_inline_trigger_trimiteri_changed(client, conn):
    """Raspunsul are header HX-Trigger=trimiteriChanged indiferent de auto_send."""
    _add_nomenclator(conn)
    sid = _insert_needs_mapping(conn)

    r = client.post(
        f"/trimitere/{sid}/mapeaza",
        data={"cod_op_service": "ITP-CHECK", "cod_prestatie": "OE-1", "auto_send": "0"},
    )
    assert r.status_code == 200
    assert r.headers.get("HX-Trigger") == "trimiteriChanged"
