from __future__ import annotations

import json
from types import SimpleNamespace

import pytest

from api.v1.modules.a76.general_catalogs.doda.alta_service import DodaAltaService


def test_build_consulta_payload_appends_numero_transaccion(monkeypatch):
    service = DodaAltaService(db=None)
    monkeypatch.setattr(
        service,
        "build_alta_payload",
        lambda **kwargs: {"base": "payload"},
    )
    monkeypatch.setattr(
        service,
        "_latest_alta_log",
        lambda *args, **kwargs: SimpleNamespace(
            id=9,
            result_json=json.dumps({"numero_transaccion": "TX-001"}),
            integration_number="INT-001",
        ),
    )

    payload = service.build_consulta_payload(
        doda_id=1, tenant_id=1, company_id=1, variant="doda", user_email="u@test.com"
    )
    assert payload["base"] == "payload"
    assert payload["numero_transaccion"] == "TX-001"


def test_build_consulta_payload_fails_when_numero_transaccion_missing(monkeypatch):
    service = DodaAltaService(db=None)
    monkeypatch.setattr(service, "build_alta_payload", lambda **kwargs: {})
    monkeypatch.setattr(
        service,
        "_latest_alta_log",
        lambda *args, **kwargs: SimpleNamespace(
            id=10, result_json=json.dumps({"other": "value"}), integration_number="INT-001"
        ),
    )

    with pytest.raises(ValueError, match="numero_transaccion"):
        service.build_consulta_payload(
            doda_id=1, tenant_id=1, company_id=1, variant="doda", user_email=""
        )


def test_build_eliminar_payload_appends_numero_integracion(monkeypatch):
    service = DodaAltaService(db=None)
    monkeypatch.setattr(service, "build_alta_payload", lambda **kwargs: {"base": "payload"})
    monkeypatch.setattr(
        service,
        "_latest_alta_log",
        lambda *args, **kwargs: SimpleNamespace(
            id=11,
            result_json="{}",
            integration_number="INT-900",
        ),
    )

    payload = service.build_eliminar_payload(
        doda_id=2, tenant_id=1, company_id=1, variant="doda", user_email="user@test.com"
    )
    assert payload["base"] == "payload"
    assert payload["numero_integracion"] == "INT-900"
