"""Tests for graph helper utilities."""

from __future__ import annotations

from collections.abc import Iterable

from azure_discovery.adt_types import ResourceNode
from azure_discovery.utils.graph_helpers import build_graph_edges, ensure_unique_nodes


def _build_node(node_id: str, name: str, dependencies: Iterable[str] | None = None) -> ResourceNode:
    return ResourceNode(
        id=node_id,
        name=name,
        type="Microsoft.Compute/virtualMachines",
        subscription_id="sub-id",
        resource_group="rg-core",
        tags={},
        dependencies=list(dependencies or []),
    )


def test_ensure_unique_nodes_preserves_last_occurrence_order() -> None:
    first_occurrence = _build_node("/subscriptions/1/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/vm-a", "vm-a-old")
    middle_node = _build_node("/subscriptions/1/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic-b", "nic-b")
    last_occurrence = _build_node("/subscriptions/1/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/vm-a", "vm-a-new")

    unique_nodes = ensure_unique_nodes([first_occurrence, middle_node, last_occurrence])

    assert [node.id for node in unique_nodes] == [
        middle_node.id,
        last_occurrence.id,
    ], "Last duplicate should retain its chronological position"
    assert unique_nodes[-1].name == "vm-a-new"


def test_build_graph_edges_creates_relationships_when_dependencies_present() -> None:
    source_node = _build_node("vm-a", "vm-a", dependencies=["nic-b", "disk-c"])
    target_node = _build_node("nic-b", "nic-b")
    unrelated_node = _build_node("vnet-x", "vnet-x")

    edges = build_graph_edges([source_node, target_node, unrelated_node], include_relationships=True)

    assert len(edges) == 1
    edge = edges[0]
    assert edge.source_id == "vm-a"
    assert edge.target_id == "nic-b"
    assert edge.relation_type == "depends_on"


def test_build_graph_edges_returns_empty_when_disabled() -> None:
    nodes: list[ResourceNode] = [
        _build_node("vm-a", "vm-a", dependencies=["nic-b"]),
        _build_node("nic-b", "nic-b"),
    ]

    edges = build_graph_edges(nodes, include_relationships=False)

    assert edges == []
