"""Prestatiile excluse de la declarare nu ajung niciodata la RAR.

content['prestatii'] pastreaza itemii exclusi (round-trip in editor), dar
payload-ul trimis efectiv la RAR (build_rar_payload, apelat din process_one)
trebuie sa contina DOAR partea declarabila. Un item exclus/fara cod nu produce
niciodata {codPrestatie: null} in payload.
"""

from __future__ import annotations

import json
import os
import tempfile

import pytest


@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()
    from app.db import get_connection, init_db
    init_db()
    conn = get_connection()
    settings = get_settings()
    yield conn, settings
    conn.close()
    get_settings.cache_clear()


_CONTENT_CU_EXCLUS = {
    "vin": "WVWZZZ1KZAW000123", "nr_inmatriculare": "B999TST",
    "data_prestatie": "2026-06-15", "odometru_final": "123456",
    "prestatii": [
        {"cod_prestatie": "OE-1", "cod_op_service": "100"},
        {"cod_prestatie": None, "cod_op_service": "200", "denumire": "Spalare", "exclus": True},
    ],
    "sistem_reparat": "null",
}


def _insert(conn, content):
    cur = conn.execute(
        "INSERT INTO submissions (idempotency_key, status, payload_json, retry_count) "
        "VALUES (?, 'queued', ?, 0)",
        (f"key-{os.urandom(4).hex()}", json.dumps(content)),
    )
    return int(cur.lastrowid)


class FakeRarCapturePayload:
    """RAR mock care retine payload-ul trimis efectiv la postPrezentare."""

    def __init__(self):
        self.sent_payload = None

    def get_finalizate(self, token):
        return []

    def post_prezentare(self, token, payload):
        self.sent_payload = payload
        return {"id": 999}


def test_process_one_nu_trimite_item_exclus_la_rar(env):
    from app.worker.__main__ import process_one
    conn, settings = env
    sid = _insert(conn, _CONTENT_CU_EXCLUS)
    rar = FakeRarCapturePayload()

    claimed = {"id": sid, "account_id": None, "content": _CONTENT_CU_EXCLUS}
    status = process_one(conn, settings, rar, "tok", claimed)

    assert status == "sent"
    assert rar.sent_payload is not None
    coduri = [p["codPrestatie"] for p in rar.sent_payload["prestatii"]]
    assert None not in coduri
    assert coduri == ["OE-1"]


def test_process_one_pastreaza_content_intact_in_db(env):
    """content['prestatii'] din DB nu se ingusteaza — doar payload-ul RAR."""
    from app.worker.__main__ import process_one
    conn, settings = env
    sid = _insert(conn, _CONTENT_CU_EXCLUS)
    rar = FakeRarCapturePayload()

    claimed = {"id": sid, "account_id": None, "content": dict(_CONTENT_CU_EXCLUS)}
    process_one(conn, settings, rar, "tok", claimed)

    row = conn.execute("SELECT payload_json FROM submissions WHERE id=?", (sid,)).fetchone()
    saved = json.loads(row["payload_json"])
    # payload_json in DB nu e atins de process_one (doar payload-ul RAR e ingustat) —
    # ramane cu ambele prestatii, inclusiv cea exclusa.
    assert len(saved["prestatii"]) == 2
