import pytest
import sys
from unittest.mock import patch, MagicMock

# Force reload of session_utils to bypass the global mock in conftest
if "session_utils" in sys.modules:
    del sys.modules["session_utils"]
import session_utils
from session_utils import create_session, validate_session, delete_session, get_user_id_from_session, track_user_ping, is_user_online

def test_create_session():
    with patch("session_utils.r") as mock_redis:
        sid = create_session(1, 10)
        assert sid is not None
        # Check if setex was called with correct key and user_id
        mock_redis.setex.assert_called_once()
        args = mock_redis.setex.call_args[0]
        assert args[0].startswith("session:")
        assert args[2] == "1"

def test_validate_session():
    with patch("session_utils.r") as mock_redis:
        mock_redis.exists.return_value = 1
        assert validate_session("test-sid") is True
        
        mock_redis.exists.return_value = 0
        assert validate_session("wrong-sid") is False

def test_track_user_ping():
    with patch("session_utils.r") as mock_redis:
        track_user_ping(5)
        mock_redis.setex.assert_called_once()
        args = mock_redis.setex.call_args[0]
        assert args[0] == "user_ping:5"
        assert args[1] == 60

def test_is_user_online():
    with patch("session_utils.r") as mock_redis:
        mock_redis.exists.return_value = 1
        assert is_user_online(5) is True
        
        mock_redis.exists.return_value = 0
        assert is_user_online(10) is False
