"""Tests for duty_teller.db.session (session_scope rollback/close, get_engine)."""

from unittest.mock import MagicMock, patch

import pytest

from duty_teller.db import session as session_mod


def test_session_scope_rollback_on_exception():
    """session_scope: on exception inside block, rollback and close are called."""
    mock_session = MagicMock()
    with patch.object(session_mod, "get_session", return_value=mock_session):
        with pytest.raises(ValueError):
            with session_mod.session_scope("sqlite:///:memory:") as s:
                assert s is mock_session
                raise ValueError("test")
    mock_session.rollback.assert_called_once()
    mock_session.close.assert_called_once()


def test_session_scope_close_on_success():
    """session_scope: on normal exit, close is called (no rollback)."""
    mock_session = MagicMock()
    with patch.object(session_mod, "get_session", return_value=mock_session):
        with session_mod.session_scope("sqlite:///:memory:") as s:
            assert s is mock_session
    mock_session.rollback.assert_not_called()
    mock_session.close.assert_called_once()


def test_get_engine_same_url_returns_same_instance():
    """get_engine: same URL returns the same engine instance."""
    session_mod._engine = None
    session_mod._SessionLocal = None
    url = "sqlite:///:memory:"
    e1 = session_mod.get_engine(url)
    e2 = session_mod.get_engine(url)
    assert e1 is e2
