from unittest import mock
import json
import uuid

from vmms.tests import base


class TestVMMSServiceAPI(base.VMMSTestCase):
    """Test VMMS service API endpoints."""

    def setUp(self):
        super(TestVMMSServiceAPI, self).setUp()
        
        # Mock database session
        self.session_patcher = mock.patch('vmms.db.sqlalchemy.database.get_session')
        self.mock_session = self.session_patcher.start()
        self.addCleanup(self.session_patcher.stop)
        
        # Mock the config module to avoid initialization
        self.config_module_patcher = mock.patch('vmms.config.init_config')
        self.mock_init_config = self.config_module_patcher.start()
        self.mock_init_config.return_value = mock.Mock()  # Return mock config
        self.addCleanup(self.config_module_patcher.stop)
        
        # Mock get_vm_details_from_source_cloud
        self.vm_details_patcher = mock.patch('vmms.api.get_vm_details_from_source_cloud')
        self.mock_get_vm_details = self.vm_details_patcher.start()
        self.addCleanup(self.vm_details_patcher.stop)
        
        # Mock policy enforcement to always allow (for functional tests)
        self.policy_patcher = mock.patch('vmms.policy.enforcer.enforce_policy')
        self.mock_enforce_policy = self.policy_patcher.start()
        self.mock_enforce_policy.return_value = True  # Always allow policy
        self.addCleanup(self.policy_patcher.stop)

    def test_healthcheck_endpoint(self):
        """Test health check endpoint."""
        response = self.client.get('/healthcheck')
        self.assertEqual(response.status_code, 200)
        data = json.loads(response.data)
        self.assertEqual(data['status'], 'ok')
        self.assertEqual(data['service'], 'vmms')

    def test_invalid_migration_id_format(self):
        """Test API with invalid migration ID format."""
        with mock.patch(
            'vmms.api.is_valid_uuid',
            return_value=False,
        ):
            response = self.client.get(
                '/v2/vms/invalid-id',
                environ_overrides={
                    'keystone.token_info': {
                        'token': {
                            'user': {
                                'id': 'test-user',
                            },
                            'project': {
                                'id': 'test-project',
                            },
                            'roles': [
                                {'name': 'vmms_operator'},
                            ],
                        },
                    },
                },
            )

        self.assertEqual(response.status_code, 400)
