

def test_protocol_v2_contract(monkeypatch):
    from app.domain.contas.client import TimApiClient

    monkeypatch.setenv("TIM_USE_MOCK_GATEWAY", "false")
    monkeypatch.setenv("TIM_GATEWAY_MODE", "real")
    monkeypatch.setenv("TIM_PROTOCOL_URL", "http://test/protocol")
    client = TimApiClient()
    captured = {}

    def fake_request(method, url, **kwargs):
        captured.update(method=method, url=url, **kwargs)
        return {"interactionProtocol": "PRT-999"}

    monkeypatch.setattr(client, "request", fake_request)
    result = client.abrir_protocolo({
        "msisdn": "11999998888",
        "socialSecNo": "12345678900",
        "customerId": "C1",
        "customerName": "Cliente Teste",
        "customerEmail": "teste@example.com",
        "customerPhone1": "11999999999",
        "accessType": "Pós-Pago",
        "serviceRequestUserId": "USR123",
        "reason1": "Vendas", "reason2": "Cancelamento", "reason3": "Retencao",
        "requestStatus": "Aberto", "status": "OPENED",
        "serviceRequestNotes": "Obs",
        "interactionCallId": "CALL-1",
        "interactionReasonId": "R1", "interactionAmount": "1", "interactionRequestSla": "SLA-1",
        "directionContact": "FROM-CLIENT", "clientId": "BFFDIGITAL", "messageId": "msg-9",
        "authorization_oam": "Bearer oam", "cn_field": "CN", "type_field": "TYPE",
    })
    assert result["interactionProtocol"] == "PRT-999"
    assert captured["method"] == "POST"
    body = captured["payload"]
    assert body["assetId"] == "11999998888"
    assert body["channel"] == "AIAGENTCR"
    assert body["serviceRequest"]["reason2"] == "Cancelamento"
    assert body["interaction"]["crmSource"] == "Siebel Pós"
    assert body["interaction"]["source"] == "AIAGENTCR"
    assert body["interaction"]["requestFlag"] is False
    assert captured["headers"]["messageId"] == "msg-9"
    assert captured["headers"]["Authorizationoam"] == "Bearer oam"


def test_rct_retry_policy_preserves_attempt_semantics():
    from app.domain.contas.rct_policy import rct_tags_for_attempt
    assert rct_tags_for_attempt("cancela_vas", 1, success=False) == ("RCT.002",)
    assert rct_tags_for_attempt("cancela_vas", 2, success=True) == ("RCT.003",)
    assert rct_tags_for_attempt("sgr_codbar", 1, success=False) == ("RCT.014",)
    assert rct_tags_for_attempt("sgr_codbar", 2, success=True) == ("RCT.015",)
    assert rct_tags_for_attempt("contestacao", 3, success=True) == ("RCT.011",)


def test_billing_analysis_anexa_transport_metadata_de_tentativas(monkeypatch):
    from app.domain.contas.client import TimApiClient
    client = TimApiClient(); client.mock = False
    monkeypatch.setenv("TIM_DIVERGENCIA_URL", "http://tim/billingAnalysis")
    def fake_request(method, url, **kwargs):
        kwargs["attempt_log"].extend([
            {"attempt": 1, "success": False, "status_code": 500, "latency_ms": 10, "error": "x"},
            {"attempt": 2, "success": True, "status_code": 200, "latency_ms": 8},
        ])
        return {"invoiceExplanation": "ok"}
    monkeypatch.setattr(client, "request", fake_request)
    result = client.billing_analysis("11999999999")
    assert result["_transport"]["rct_operation"] == "base_conhecimento"
    assert [a["attempt"] for a in result["_transport"]["attempts"]] == [1, 2]
