# #region Test.PreviewSessionSerializer [C:2] [TYPE Module] [SEMANTICS test, translate, preview, serialize]
# @BRIEF Tests for preview_session_serializer.py — serialize_preview_record.
# @RELATION BINDS_TO -> [preview_session_serializer]
# @TEST_CONTRACT: serialize_preview_record -> dict | serializes TranslationPreviewRecord
# @TEST_EDGE: empty_languages
# @TEST_EDGE: no_source_language_detected

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

import os
os.environ.setdefault("SECRET_KEY", "test-secret-key-for-testing")
os.environ.setdefault("DATABASE_URL", "sqlite:///:memory:")
os.environ.setdefault("AUTH_DATABASE_URL", "sqlite:///:memory:")

from unittest.mock import MagicMock

from src.plugins.translate.preview_session_serializer import serialize_preview_record


def _make_language(language_code="ru", **kwargs):
    lang = MagicMock()
    lang.language_code = language_code
    lang.source_language_detected = kwargs.get("source_language_detected", "en")
    lang.translated_value = kwargs.get("translated_value", "привет")
    lang.final_value = kwargs.get("final_value", "привет")
    lang.user_edit = kwargs.get("user_edit", None)
    lang.status = kwargs.get("status", "translated")
    lang.needs_review = kwargs.get("needs_review", False)
    return lang


def _make_record(**kwargs):
    r = MagicMock(spec=object)
    r.id = kwargs.get("id", "rec-1")
    r.source_sql = kwargs.get("source_sql", "SELECT * FROM t")
    r.target_sql = kwargs.get("target_sql", "SELECT * FROM t_translated")
    r.source_object_type = kwargs.get("source_object_type", "table")
    r.source_object_id = kwargs.get("source_object_id", "obj-1")
    r.source_object_name = kwargs.get("source_object_name", "my_table")
    r.status = kwargs.get("status", "done")
    r.feedback = kwargs.get("feedback", None)
    r.languages = kwargs.get("languages", [])
    return r


class TestSerializePreviewRecord:
    """serialize_preview_record — serialize TranslationPreviewRecord."""

    def test_basic_serialization(self):
        """Full record with languages returns all fields."""
        lang_ru = _make_language(language_code="ru", final_value="привет")
        lang_de = _make_language(language_code="de", final_value="hallo")
        record = _make_record(languages=[lang_ru, lang_de])

        result = serialize_preview_record(record)

        assert result["id"] == "rec-1"
        assert result["source_sql"] == "SELECT * FROM t"
        assert result["target_sql"] == "SELECT * FROM t_translated"
        assert result["source_object_type"] == "table"
        assert result["source_object_id"] == "obj-1"
        assert result["source_object_name"] == "my_table"
        assert result["status"] == "done"
        assert result["feedback"] is None
        assert result["needs_review"] is False
        assert len(result["languages"]) == 2
        assert result["languages"][0]["language_code"] == "ru"
        assert result["languages"][0]["final_value"] == "привет"
        assert result["languages"][1]["language_code"] == "de"

    def test_empty_languages(self):
        """Record with no languages returns empty languages list."""
        record = _make_record(languages=[])

        result = serialize_preview_record(record)

        assert result["languages"] == []
        assert result["source_language_detected"] is None
        assert result["needs_review"] is False

    def test_languages_is_none(self):
        """Record with None languages returns empty list."""
        record = _make_record(languages=None)

        result = serialize_preview_record(record)

        assert result["languages"] == []

    def test_no_source_language_detected(self):
        """Language without source_language_detected returns None."""
        lang = _make_language(source_language_detected=None)
        record = _make_record(languages=[lang])

        result = serialize_preview_record(record)

        assert result["source_language_detected"] is None

    def test_source_language_detected_present(self):
        """Language with source_language_detected returns it."""
        lang = _make_language(source_language_detected="fr")
        record = _make_record(languages=[lang])

        result = serialize_preview_record(record)

        assert result["source_language_detected"] == "fr"

    def test_needs_review_from_language(self):
        """needs_review comes from first language entry."""
        lang = _make_language(needs_review=True)
        record = _make_record(languages=[lang])

        result = serialize_preview_record(record)

        assert result["needs_review"] is True

    def test_user_edit_present(self):
        """user_edit field is included when present."""
        lang = _make_language(user_edit="пользовательский перевод")
        record = _make_record(languages=[lang])

        result = serialize_preview_record(record)

        assert result["languages"][0]["user_edit"] == "пользовательский перевод"
# #endregion Test.PreviewSessionSerializer
