import unittest
from unittest.mock import patch, MagicMock
from flask import Flask
from app.routes.api import api_bp

# filepath: app/routes/test_api.py

class TestGetChatHistory(unittest.TestCase):
    def setUp(self):
        # Create a Flask app and register the blueprint
        self.app = Flask(__name__)
        self.app.register_blueprint(api_bp)
        self.client = self.app.test_client()

    @patch('app.routes.api.mysql.connection.cursor')
    def test_get_chat_history_success(self, mock_cursor):
        # Mock database response
        mock_cursor.return_value.__enter__.return_value.fetchall.return_value = [
            ('user', 'Hello', None),
            ('assistant', 'Hi, how can I help you?', None)
        ]

        # Simulate a GET request with session_id
        response = self.client.get('/api/1/chat-history?session_id=test-session-id')

        # Assert the response
        self.assertEqual(response.status_code, 200)
        self.assertIn('success', response.json)
        self.assertTrue(response.json['success'])
        self.assertIn('history', response.json)
        self.assertEqual(len(response.json['history']), 2)

    def test_get_chat_history_missing_session_id(self):
        # Simulate a GET request without session_id
        response = self.client.get('/api/1/chat-history')

        # Assert the response
        self.assertEqual(response.status_code, 400)
        self.assertIn('success', response.json)
        self.assertFalse(response.json['success'])
        self.assertIn('error', response.json)
        self.assertEqual(response.json['error'], 'Session ID is required')

    @patch('app.routes.api.mysql.connection.cursor')
    def test_get_chat_history_db_error(self, mock_cursor):
        # Simulate a database error
        mock_cursor.return_value.__enter__.side_effect = Exception('Database error')

        # Simulate a GET request with session_id
        response = self.client.get('/api/1/chat-history?session_id=test-session-id')

        # Assert the response
        self.assertEqual(response.status_code, 500)
        self.assertIn('success', response.json)
        self.assertFalse(response.json['success'])
        self.assertIn('error', response.json)
        self.assertEqual(response.json['error'], 'Database error')

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