# #region Test.DatasetReview.Mutations [C:4] [TYPE Module] [SEMANTICS test, dataset, review, mutation, persistence, coverage]
# @BRIEF Tests for SessionRepositoryMutations — save_profile_and_findings, save_recovery_state, save_preview, save_run_context.
# @RELATION BINDS_TO -> [SessionRepositoryMutations]

import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent.parent.parent / "src"))

from unittest.mock import MagicMock

import pytest

from src.models.dataset_review import (
    CompiledPreview,
    DatasetProfile,
    DatasetReviewSession,
    DatasetRunContext,
    ValidationFinding,
)


def _require_session_version(session, expected_version):
    pass


def _commit_session_mutation(session, **kwargs):
    pass


# ── save_profile_and_findings ──

class TestSaveProfileAndFindings:
    """save_profile_and_findings — profile persistence and finding replacement."""

    def test_with_profile_and_findings(self):
        from src.services.dataset_review.repositories.repository_pkg._mutations import save_profile_and_findings

        db = MagicMock()
        mock_session = MagicMock(spec=DatasetReviewSession)
        get_owned = lambda sid, uid: mock_session

        profile = MagicMock(spec=DatasetProfile)
        findings = [MagicMock(spec=ValidationFinding), MagicMock(spec=ValidationFinding)]

        result = save_profile_and_findings(
            db, MagicMock(), get_owned,
            _require_session_version, _commit_session_mutation,
            "sess_1", "user_1", profile, findings,
        )
        assert result is mock_session

    def test_with_version_check(self):
        from src.services.dataset_review.repositories.repository_pkg._mutations import save_profile_and_findings

        db = MagicMock()
        mock_session = MagicMock(spec=DatasetReviewSession)
        get_owned = lambda sid, uid: mock_session
        called_version = [None]
        def require_ver(session, expected_version):
            called_version[0] = expected_version

        profile = MagicMock(spec=DatasetProfile)
        save_profile_and_findings(
            db, MagicMock(), get_owned,
            require_ver, _commit_session_mutation,
            "sess_1", "user_1", profile, [],
            expected_version=5,
        )
        assert called_version[0] == 5

    def test_with_existing_profile_merge(self):
        from src.services.dataset_review.repositories.repository_pkg._mutations import save_profile_and_findings

        db = MagicMock()
        mock_session = MagicMock(spec=DatasetReviewSession)
        get_owned = lambda sid, uid: mock_session

        existing_profile = MagicMock(spec=DatasetProfile)
        existing_profile.profile_id = "profile_old"
        mock_db_result = MagicMock()
        mock_db_result.first.return_value = existing_profile
        db.query.return_value.filter_by.return_value = mock_db_result

        new_profile = MagicMock(spec=DatasetProfile)
        save_profile_and_findings(
            db, MagicMock(), get_owned,
            _require_session_version, _commit_session_mutation,
            "sess_1", "user_1", new_profile, [],
        )
        assert new_profile.profile_id == "profile_old"

    def test_no_profile_skip_merge(self):
        from src.services.dataset_review.repositories.repository_pkg._mutations import save_profile_and_findings

        db = MagicMock()
        mock_session = MagicMock(spec=DatasetReviewSession)
        get_owned = lambda sid, uid: mock_session

        save_profile_and_findings(
            db, MagicMock(), get_owned,
            _require_session_version, _commit_session_mutation,
            "sess_1", "user_1", None, [],
        )
        db.merge.assert_not_called()


# ── save_recovery_state (no event_logger param!) ──

class TestSaveRecoveryState:
    """save_recovery_state — persist imported filters, template variables, execution mappings."""

    def test_with_all_data(self):
        from src.services.dataset_review.repositories.repository_pkg._mutations import save_recovery_state

        db = MagicMock()
        mock_session = MagicMock(spec=DatasetReviewSession)
        mock_session.session_id = "sess_1"
        get_owned = lambda sid, uid: mock_session
        load_detail = lambda sid, uid: mock_session

        filters = [MagicMock()]
        variables = [MagicMock()]
        mappings = [MagicMock()]

        # No event_logger in save_recovery_state signature!
        result = save_recovery_state(
            db, get_owned,
            _require_session_version, _commit_session_mutation,
            load_detail,
            "sess_1", "user_1", filters, variables, mappings,
        )
        assert result is mock_session

    def test_with_version_check(self):
        from src.services.dataset_review.repositories.repository_pkg._mutations import save_recovery_state

        db = MagicMock()
        mock_session = MagicMock(spec=DatasetReviewSession)
        get_owned = lambda sid, uid: mock_session
        load_detail = lambda sid, uid: mock_session
        called_version = [None]
        def require_ver(session, expected_version):
            called_version[0] = expected_version

        # No event_logger in save_recovery_state signature!
        save_recovery_state(
            db, get_owned,
            require_ver, _commit_session_mutation,
            load_detail,
            "sess_1", "user_1", [], [], [],
            expected_version=3,
        )
        assert called_version[0] == 3


# ── save_preview (no event_logger param!) ──

class TestSavePreview:
    """save_preview — persist compiled preview."""

    def test_save_preview(self):
        from src.services.dataset_review.repositories.repository_pkg._mutations import save_preview

        db = MagicMock()
        mock_session = MagicMock(spec=DatasetReviewSession)
        get_owned = lambda sid, uid: mock_session

        preview = MagicMock(spec=CompiledPreview)
        preview.preview_id = "prev_1"

        # No event_logger in save_preview signature!
        result = save_preview(
            db, get_owned,
            _require_session_version, _commit_session_mutation,
            "sess_1", "user_1", preview,
        )
        assert result is preview

    def test_with_version_check(self):
        from src.services.dataset_review.repositories.repository_pkg._mutations import save_preview

        db = MagicMock()
        mock_session = MagicMock(spec=DatasetReviewSession)
        get_owned = lambda sid, uid: mock_session
        called_version = [None]
        def require_ver(session, expected_version):
            called_version[0] = expected_version

        preview = MagicMock(spec=CompiledPreview)
        # No event_logger in save_preview signature!
        save_preview(
            db, get_owned,
            require_ver, _commit_session_mutation,
            "sess_1", "user_1", preview,
            expected_version=2,
        )
        assert called_version[0] == 2


# ── save_run_context (no event_logger param!) ──

class TestSaveRunContext:
    """save_run_context — persist run context audit snapshot."""

    def test_save_run_context(self):
        from src.services.dataset_review.repositories.repository_pkg._mutations import save_run_context

        db = MagicMock()
        mock_session = MagicMock(spec=DatasetReviewSession)
        get_owned = lambda sid, uid: mock_session

        run_context = MagicMock(spec=DatasetRunContext)
        run_context.run_context_id = "ctx_1"

        # No event_logger in save_run_context signature!
        result = save_run_context(
            db, get_owned,
            _require_session_version, _commit_session_mutation,
            "sess_1", "user_1", run_context,
        )
        assert result is run_context

    def test_with_version_check(self):
        from src.services.dataset_review.repositories.repository_pkg._mutations import save_run_context

        db = MagicMock()
        mock_session = MagicMock(spec=DatasetReviewSession)
        get_owned = lambda sid, uid: mock_session
        called_version = [None]
        def require_ver(session, expected_version):
            called_version[0] = expected_version

        run_context = MagicMock(spec=DatasetRunContext)
        # No event_logger in save_run_context signature!
        save_run_context(
            db, get_owned,
            require_ver, _commit_session_mutation,
            "sess_1", "user_1", run_context,
            expected_version=7,
        )
        assert called_version[0] == 7
# #endregion Test.DatasetReview.Mutations
