
import unittest
from unittest.mock import Mock
from datetime import datetime
from analogai.foundation.extensions.fallback import Fallback, FallbackService
from analogai.foundation.extensions.fallback.repositories import FallbackRepository


class TestFallbackService(unittest.TestCase):
    def setUp(self):
        self.mock_fallback_repository = Mock(spec=FallbackRepository)
        self.fallback_service = FallbackService(self.mock_fallback_repository)
        self.sample_fallback = Fallback(
            user_id="user-123",
            agent_id="agent-456",
            user_question="Test question",
            id="fallback-789",
            timestamp=datetime.utcnow()
        )

    def test_create_fallback_success(self):
        self.mock_fallback_repository.create.return_value = self.sample_fallback

        result = self.fallback_service.create(
            user_id="user-123",
            agent_id="agent-456",
            user_question="Test question"
        )

        self.mock_fallback_repository.create.assert_called_once()
        created_fallback = self.mock_fallback_repository.create.call_args[0][0]
        self.assertEqual(created_fallback.user_id, "user-123")
        self.assertEqual(created_fallback.agent_id, "agent-456")
        self.assertEqual(created_fallback.user_question, "Test question")
        self.assertEqual(result, self.sample_fallback)

    def test_find_by_agent_id_success(self):
        fallbacks = [self.sample_fallback]
        self.mock_fallback_repository.find_by_agent_id.return_value = fallbacks

        result = self.fallback_service.find_by_agent_id("agent-456")

        self.mock_fallback_repository.find_by_agent_id.assert_called_once_with("agent-456")
        self.assertEqual(result, fallbacks)

    def test_find_by_agent_id_not_found(self):
        self.mock_fallback_repository.find_by_agent_id.return_value = []

        result = self.fallback_service.find_by_agent_id("non-existent")

        self.mock_fallback_repository.find_by_agent_id.assert_called_once_with("non-existent")
        self.assertEqual(result, [])

    def test_find_by_id_success(self):
        self.mock_fallback_repository.find_by_id.return_value = self.sample_fallback

        result = self.fallback_service.find_by_id("fallback-789")

        self.mock_fallback_repository.find_by_id.assert_called_once_with("fallback-789")
        self.assertEqual(result, self.sample_fallback)

    def test_find_by_id_not_found(self):
        self.mock_fallback_repository.find_by_id.return_value = None

        result = self.fallback_service.find_by_id("non-existent")

        self.mock_fallback_repository.find_by_id.assert_called_once_with("non-existent")
        self.assertIsNone(result)


if __name__ == '__main__':
    unittest.main()
