"""
Tests for Celery embedding tasks.

Tasks are tested with CELERY_TASK_ALWAYS_EAGER=True for synchronous execution.
"""

from unittest.mock import MagicMock, patch

from django.test import TestCase, override_settings


@override_settings(CELERY_TASK_ALWAYS_EAGER=True)
class EmbedItemTaskTests(TestCase):
    """Tests for the embed_item task."""

    @patch("library.tasks.EmbeddingPipeline")
    def test_embed_item_success(self, mock_pipeline_cls):
        from library.tasks import embed_item

        mock_pipeline = MagicMock()
        mock_pipeline.process_item.return_value = {
            "chunks_created": 10,
            "images_stored": 2,
            "model_name": "test-model",
        }
        mock_pipeline_cls.return_value = mock_pipeline

        result = embed_item("test-uid-123")

        self.assertTrue(result["success"])
        self.assertEqual(result["item_uid"], "test-uid-123")
        mock_pipeline.process_item.assert_called_once()

    @patch("library.tasks.EmbeddingPipeline")
    def test_embed_item_failure(self, mock_pipeline_cls):
        from library.tasks import embed_item

        mock_pipeline = MagicMock()
        mock_pipeline.process_item.side_effect = ValueError("Item not found")
        mock_pipeline_cls.return_value = mock_pipeline

        result = embed_item("nonexistent-uid")

        self.assertFalse(result["success"])
        self.assertIn("error", result)


@override_settings(CELERY_TASK_ALWAYS_EAGER=True)
class ReembedItemTaskTests(TestCase):
    """Tests for the reembed_item task."""

    @patch("library.tasks.EmbeddingPipeline")
    def test_reembed_item_success(self, mock_pipeline_cls):
        from library.tasks import reembed_item

        mock_pipeline = MagicMock()
        mock_pipeline.reprocess_item.return_value = {
            "chunks_created": 5,
            "images_stored": 1,
            "model_name": "test-model",
        }
        mock_pipeline_cls.return_value = mock_pipeline

        result = reembed_item("test-uid-123")

        self.assertTrue(result["success"])
        mock_pipeline.reprocess_item.assert_called_once()


class ResolveUserTests(TestCase):
    """Tests for the _resolve_user helper."""

    def test_none_user_id(self):
        from library.tasks import _resolve_user

        self.assertIsNone(_resolve_user(None))

    def test_zero_user_id(self):
        from library.tasks import _resolve_user

        self.assertIsNone(_resolve_user(0))

    def test_invalid_user_id(self):
        from library.tasks import _resolve_user

        self.assertIsNone(_resolve_user(999999))
