"""Integration tests for ECMSync.impersonate().

Requires a running ECM server at localhost:4000.
"""

import unittest

from ecmind_blue_client.ecm import ECM, ECMSystemRole
from ecmind_blue_client.pool import SyncPoolClient
from tests._test_settings import ECM_SERVERS, ECM_USERNAME, ECM_PASSWORD


class TestEcmImpersonateSync(unittest.TestCase):
    """Integration tests for ECMSync.impersonate() — requires localhost:4000."""

    @classmethod
    def setUpClass(cls):
        cls.client = SyncPoolClient(servers=ECM_SERVERS, username=ECM_USERNAME, password=ECM_PASSWORD)
        cls.ecm = ECM(cls.client)

    @classmethod
    def tearDownClass(cls):
        del cls.client

    def test_impersonate_returns_ecm_instance(self):
        """impersonate() returns an instance of the same ECM type."""
        ecm_user = self.ecm.impersonate("root")

        self.assertIsInstance(ecm_user, type(self.ecm))

    def test_impersonate_direct_usage_works(self):
        """The impersonated instance can execute DMS operations without a context manager."""
        ecm_user = self.ecm.impersonate("root")
        result = ecm_user.security.roles()

        self.assertIsInstance(result, list)
        self.assertGreater(len(result), 0)

    def test_impersonate_context_manager_works(self):
        """The impersonated instance can be used as a context manager."""
        with self.ecm.impersonate("root") as ecm_user:
            result = ecm_user.security.roles()

        self.assertIsInstance(result, list)
        self.assertGreater(len(result), 0)

    def test_impersonate_contains_admin_start_role(self):
        """The root user has the ADMIN_START system role when impersonated."""
        with self.ecm.impersonate("root") as ecm_user:
            result = ecm_user.security.roles()

        self.assertIn(ECMSystemRole.ADMIN_START, result)
