"""Tests for user_id propagation."""
from __future__ import annotations

import staso as st
from staso.context import user_id_var


class TestUserId:
    def test_user_id_in_conversation(self, capturing):
        with st.conversation("conv-1", user_id="user-42"):
            tracer = st.get_client().provider.get_tracer()
            with tracer.start_as_current_span("test"):
                pass

        assert len(capturing) == 1
        assert capturing[0]["user_id"] == "user-42"

    def test_user_id_empty_by_default(self, capturing):
        tracer = st.get_client().provider.get_tracer()
        with tracer.start_as_current_span("test"):
            pass

        assert capturing[0]["user_id"] == ""

    def test_user_id_resets_after_context(self, capturing):
        with st.conversation("conv-1", user_id="user-42"):
            pass

        assert user_id_var.get("") == ""

        tracer = st.get_client().provider.get_tracer()
        with tracer.start_as_current_span("after"):
            pass

        assert capturing[0]["user_id"] == ""

    def test_user_id_propagates_to_children(self, capturing):
        with st.conversation("conv-1", user_id="user-99"):
            tracer = st.get_client().provider.get_tracer()
            with tracer.start_as_current_span("parent"):
                with tracer.start_as_current_span("child"):
                    pass

        assert len(capturing) == 2
        assert capturing[0]["user_id"] == "user-99"
        assert capturing[1]["user_id"] == "user-99"

    def test_conversation_without_user_id(self, capturing):
        with st.conversation("conv-1"):
            tracer = st.get_client().provider.get_tracer()
            with tracer.start_as_current_span("test"):
                pass

        assert capturing[0]["user_id"] == ""
