"""Tests for account manager."""

from unittest.mock import MagicMock, patch

import boto3
import pytest
from moto import mock_aws

from ai_org.core.account_manager import AccountManager


@pytest.fixture
def mock_manager():
    """Create an AccountManager with mocked AWS clients."""
    with patch.object(AccountManager, "__init__", lambda self, **kw: None):
        manager = AccountManager.__new__(AccountManager)
        manager.aws = MagicMock()
        manager.aws.region = "us-east-1"
        manager.org_client = MagicMock()
        manager.config = MagicMock()
        return manager


@pytest.mark.unit
class TestAccountManager:
    @mock_aws
    def test_init(self):
        # Create mock org so the Organizations client doesn't fail
        client = boto3.client("organizations", region_name="us-east-1")
        client.create_organization(FeatureSet="ALL")
        manager = AccountManager(profile=None, region="us-east-1")
        assert manager is not None

    def test_list_accounts(self, mock_manager):
        mock_manager.org_client.list_accounts.return_value = {
            "Accounts": [
                {"Id": "123456789012", "Name": "TestAccount", "Status": "ACTIVE"},
                {"Id": "987654321098", "Name": "ProdAccount", "Status": "ACTIVE"},
            ]
        }
        accounts = mock_manager.org_client.list_accounts()["Accounts"]
        assert len(accounts) == 2
        assert accounts[0]["Name"] == "TestAccount"

    def test_get_account(self, mock_manager):
        mock_manager.org_client.describe_account.return_value = {
            "Account": {
                "Id": "123456789012",
                "Name": "TestAccount",
                "Email": "test@example.com",
                "Status": "ACTIVE",
            }
        }
        result = mock_manager.org_client.describe_account(AccountId="123456789012")
        assert result["Account"]["Id"] == "123456789012"

    @mock_aws
    def test_list_accounts_with_ou_integration(self):
        client = boto3.client("organizations", region_name="us-east-1")
        client.create_organization(FeatureSet="ALL")
        root_id = client.list_roots()["Roots"][0]["Id"]
        client.create_organizational_unit(ParentId=root_id, Name="Workloads")

        manager = AccountManager(profile=None, region="us-east-1")
        result = manager.list_accounts_with_ou()
        # Management account should appear
        assert isinstance(result, list)
