"""Regresie PRD 5.19 US-002 — re-snapshot `held` pe caile de re-punere in coada.

Bug (gasit la /code-review high): create_prezentari (reactivare) si reresolve_account
re-calculau `held` din comutatorul contului la tranzitia -> queued, dar caile de
re-punere din dashboard/admin (requeue_submission, corectie, repune-cu-cod, bulk-fix)
lasau `held` pe valoarea VECHE. Consecinta: un rand ingerat pe Auto ON (held=0) care a
esuat, apoi contul trecut pe Auto OFF, la re-punere pastra held=0 -> worker-ul il
auto-trimitea la RAR (FINALIZATA ireversibil) desi contul e Auto OFF.

Testam sursa comuna requeue_submission (backing API /repune + web) pe ambele directii.
"""

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()
    yield conn
    conn.close()
    get_settings.cache_clear()


_CONTENT = {
    "vin": "WVWZZZ1KZAW000123", "nr_inmatriculare": "B999TST",
    "data_prestatie": "2026-06-15", "odometru_final": "123456",
    "prestatii": [{"cod_prestatie": "OE-1"}], "sistem_reparat": "null",
}


def _insert_error(conn, account_id, held):
    cur = conn.execute(
        "INSERT INTO submissions (idempotency_key, status, payload_json, account_id, held) "
        "VALUES (?, 'error', ?, ?, ?)",
        (f"key-{os.urandom(4).hex()}", json.dumps(_CONTENT), account_id, held),
    )
    return int(cur.lastrowid)


def _held(conn, sid):
    return conn.execute("SELECT held FROM submissions WHERE id=?", (sid,)).fetchone()["held"]


def test_requeue_tine_randul_cand_cont_auto_off(env):
    """Auto OFF + rand held=0 (ingerat pe Auto ON) -> requeue re-snapshot -> held=1.

    Fara fix worker-ul l-ar auto-trimite desi contul e Auto OFF.
    """
    from app.accounts import create_account, set_auto_send
    from app.submissions_admin import requeue_submission

    conn = env
    acct = create_account(conn, "Service AutoOff", active=True)
    set_auto_send(conn, acct, False)  # cont Auto OFF
    sid = _insert_error(conn, acct, held=0)  # rand cu held vechi (de pe Auto ON)

    requeue_submission(conn, acct, sid)

    assert _held(conn, sid) == 1, "rand repus pe cont Auto OFF trebuie TINUT (held=1)"


def test_requeue_elibereaza_randul_cand_cont_auto_on(env):
    """Auto ON + rand held=1 (ingerat pe Auto OFF) -> requeue re-snapshot -> held=0.

    Altfel randul ar ramane blocat (worker sare peste held=1) dupa ce contul e Auto ON.
    """
    from app.accounts import create_account, set_auto_send
    from app.submissions_admin import requeue_submission

    conn = env
    acct = create_account(conn, "Service AutoOn", active=True)
    set_auto_send(conn, acct, True)  # cont Auto ON
    sid = _insert_error(conn, acct, held=1)  # rand cu held vechi (de pe Auto OFF)

    requeue_submission(conn, acct, sid)

    assert _held(conn, sid) == 0, "rand repus pe cont Auto ON NU trebuie tinut (held=0)"
