"""Tests for session state thread safety."""

import threading

from cloudsense_dx_mcp.session import get_session_org, set_session_org

# Reset module state before/after tests
import cloudsense_dx_mcp.session as _session_mod


def setup_function():
    _session_mod._session_org_alias = None


def teardown_function():
    _session_mod._session_org_alias = None


def test_set_and_get():
    set_session_org("my-org")
    assert get_session_org() == "my-org"


def test_returns_none_initially():
    assert get_session_org() is None


def test_overwrites():
    set_session_org("org-a")
    set_session_org("org-b")
    assert get_session_org() == "org-b"


def test_concurrent_access():
    """Verify no corruption under concurrent writes from multiple threads."""
    results = []
    barrier = threading.Barrier(20)

    def writer(alias: str):
        barrier.wait()
        set_session_org(alias)
        results.append(get_session_org())

    threads = [threading.Thread(target=writer, args=(f"org-{i}",)) for i in range(20)]
    for t in threads:
        t.start()
    for t in threads:
        t.join()

    assert len(results) == 20
    final = get_session_org()
    assert final is not None
    assert final.startswith("org-")
