"""Tests for GCP Assured Workloads landing zone detection."""

from __future__ import annotations

import importlib
import sys
from unittest.mock import MagicMock, patch


def _setup_gcp_mocks():
    """Create and install mock GCP SDK modules, return asset_v1 mock."""
    mock_asset_v1 = MagicMock()
    mock_google = MagicMock()
    mock_google_cloud = MagicMock()

    modules = {
        "google": mock_google,
        "google.cloud": mock_google_cloud,
        "google.cloud.asset_v1": mock_asset_v1,
    }
    return modules, mock_asset_v1


class TestGCPLandingZone:
    def test_no_sdk(self) -> None:
        from complyform.core.scanner.landing_zone_gcp import (
            detect_gcp_landing_zone,
        )

        with patch("builtins.__import__", side_effect=ImportError):
            result = detect_gcp_landing_zone("proj-1", None)
        assert result.detected is False

    def test_no_workloads_found(self) -> None:
        modules, mock_asset_v1 = _setup_gcp_mocks()

        mock_client = MagicMock()
        mock_asset_v1.AssetServiceClient.return_value = mock_client
        mock_client.search_all_resources.return_value = []

        with patch.dict(sys.modules, modules):
            import complyform.core.scanner.landing_zone_gcp as mod

            importlib.reload(mod)
            result = mod.detect_gcp_landing_zone("proj-1", None)

        assert result.detected is False

    def test_api_error_returns_not_detected(self) -> None:
        modules, mock_asset_v1 = _setup_gcp_mocks()

        mock_client = MagicMock()
        mock_asset_v1.AssetServiceClient.return_value = mock_client
        mock_client.search_all_resources.side_effect = Exception("API error")

        with patch.dict(sys.modules, modules):
            import complyform.core.scanner.landing_zone_gcp as mod

            importlib.reload(mod)
            result = mod.detect_gcp_landing_zone("proj-1", None)

        assert result.detected is False
