"""Tests for account factory."""

from unittest.mock import MagicMock, patch

import pytest

from ai_org.core.account_factory import AccountFactory


@pytest.fixture
def mock_factory():
    """Create an AccountFactory with mocked clients."""
    with patch.object(AccountFactory, "__init__", lambda self, **kw: None):
        factory = AccountFactory.__new__(AccountFactory)
        factory.aws = MagicMock()
        factory.service_catalog = MagicMock()
        factory.org_client = MagicMock()
        factory._product_id = None
        factory._artifact_id = None
        return factory


@pytest.mark.unit
class TestAccountFactory:
    def test_init(self):
        with patch("ai_org.core.aws_client.AWSClient"):
            factory = AccountFactory(profile=None, region="us-east-1")
            assert factory is not None

    def test_find_account_factory_product_cached(self, mock_factory):
        mock_factory._product_id = "prod-123"
        mock_factory._artifact_id = "art-456"
        result = mock_factory.find_account_factory_product()
        assert result == ("prod-123", "art-456")
        mock_factory.service_catalog.search_products.assert_not_called()

    def test_find_account_factory_product_search(self, mock_factory):
        mock_factory.service_catalog.search_products.return_value = {
            "ProductViewSummaries": [
                {"ProductId": "prod-new", "Name": "AWS Control Tower Account Factory"}
            ]
        }
        mock_factory.service_catalog.list_provisioning_artifacts.return_value = {
            "ProvisioningArtifactDetails": [
                {
                    "Id": "art-new",
                    "Active": True,
                    "Guidance": "DEFAULT",
                }
            ]
        }
        result = mock_factory.find_account_factory_product()
        assert result == ("prod-new", "art-new")

    def test_find_account_factory_product_not_found(self, mock_factory):
        mock_factory.service_catalog.search_products.return_value = {"ProductViewSummaries": []}
        with pytest.raises(Exception, match="Account Factory product not found"):
            mock_factory.find_account_factory_product()
