import types

from py_azpe import AzurePolicyEngine


class DummyAssignmentsClient:
    def __init__(self):
        self.created = []

    def create(self, scope, name, params):
        self.created.append((scope, name, params))
        return types.SimpleNamespace(
            as_dict=lambda: {
                "scope": scope,
                "name": name,
                "params_type": type(params).__name__,
            }
        )


class DummyPolicyClient:
    def __init__(self):
        self.policy_assignments = DummyAssignmentsClient()


def _patch_policy_client(monkeypatch, dummy):
    monkeypatch.setitem(
        __import__("sys").modules,
        "azure.mgmt.resource",
        types.SimpleNamespace(PolicyClient=lambda cred, sub: dummy),
    )


def test_create_assignment_subscription_scope(monkeypatch, tmp_path):
    engine = AzurePolicyEngine(backend="sdk", policy_dir=str(tmp_path))
    dummy = DummyPolicyClient()
    _patch_policy_client(monkeypatch, dummy)

    assign = {
        "properties": {
            "displayName": "Sub Assign",
            "policyDefinitionId": "/subscriptions/0000/providers/Microsoft.Authorization/policyDefinitions/pd1",
        }
    }
    scope = "/subscriptions/0000"
    _ = engine.create_assignment("subAssign", assign, scope=scope)

    assert dummy.policy_assignments.created
    cscope, cname, _ = dummy.policy_assignments.created[0]
    assert cscope == scope
    assert cname == "subAssign"


def test_create_assignment_resource_group_scope(monkeypatch, tmp_path):
    engine = AzurePolicyEngine(backend="sdk", policy_dir=str(tmp_path))
    dummy = DummyPolicyClient()
    _patch_policy_client(monkeypatch, dummy)

    assign = {
        "properties": {
            "displayName": "RG Assign",
            "policyDefinitionId": "/subscriptions/0000/resourceGroups/rg1/providers/Microsoft.Authorization/policyDefinitions/pd1",
        }
    }
    scope = "/subscriptions/0000/resourceGroups/rg1"
    _ = engine.create_assignment("rgAssign", assign, scope=scope)

    assert dummy.policy_assignments.created
    cscope, cname, _ = dummy.policy_assignments.created[0]
    assert cscope == scope
    assert cname == "rgAssign"
