"""Tests for Catch Error node."""

import pytest

from fw_nodes_core.nodes.catch_error import CatchErrorNode


@pytest.mark.asyncio
async def test_catch_error_passes_through_inputs(node_execution_context):
    """Test that Catch Error node passes through its inputs as output.

    The executor populates this node's inputs with error details.
    The node just passes them through.
    """
    node = CatchErrorNode()
    inputs = {
        "error_message": "Node failed: connection timeout",
        "failed_node_id": "http-node-123",
        "failed_node_label": "Fetch API Data",
        "failed_node_type": "http_request",
        "errors": [
            {
                "error_message": "Node failed: connection timeout",
                "failed_node_id": "http-node-123",
                "failed_node_label": "Fetch API Data",
                "failed_node_type": "http_request",
            }
        ],
    }

    result = await node.execute(inputs, node_execution_context)
    output = result.model_dump(exclude_none=True, by_alias=True)

    assert output["error_message"] == "Node failed: connection timeout"
    assert output["failed_node_id"] == "http-node-123"
    assert output["failed_node_label"] == "Fetch API Data"
    assert output["failed_node_type"] == "http_request"
    assert len(output["errors"]) == 1


@pytest.mark.asyncio
async def test_catch_error_multiple_errors(node_execution_context):
    """Test Catch Error with multiple parallel errors."""
    node = CatchErrorNode()
    inputs = {
        "error_message": "First error",
        "failed_node_id": "node-1",
        "failed_node_label": "Node 1",
        "failed_node_type": "http_request",
        "errors": [
            {
                "error_message": "First error",
                "failed_node_id": "node-1",
                "failed_node_label": "Node 1",
                "failed_node_type": "http_request",
            },
            {
                "error_message": "Second error",
                "failed_node_id": "node-2",
                "failed_node_label": "Node 2",
                "failed_node_type": "delay",
            },
        ],
    }

    result = await node.execute(inputs, node_execution_context)
    output = result.model_dump(exclude_none=True, by_alias=True)

    assert output["error_message"] == "First error"
    assert len(output["errors"]) == 2
    assert output["errors"][1]["failed_node_id"] == "node-2"


@pytest.mark.asyncio
async def test_catch_error_metadata():
    """Test Catch Error node metadata is correct."""
    node = CatchErrorNode()
    metadata = node.get_metadata()

    assert metadata.name == "Catch Error"
    assert metadata.category == "logic"
    assert metadata.handles.inputs == []  # No input connections
    assert len(metadata.handles.outputs) == 1  # One output handle
