// r8r: rust port of n8n.io
// Initial author: Michael Cochran <mcochran@cochranblock.org>
// Built for: Tanner Woodrum, intended cofounder
// License: Unlicense (public domain dedication, see UNLICENSE)
//
// `execution_data` — emit metadata about the current execution
// (workflow name, execution_id, item index). Useful for logging /
// audit trails downstream.

use async_trait::async_trait;
use crate::core::error::NodeError;
use crate::core::types::*;
use crate::engine::{ExecuteCtx, Node, NodeFactory};
use serde_json::json;
use std::sync::Arc;

pub struct ExecutionDataNode;

static META: NodeMetadata = NodeMetadata {
    name: "execution_data",
    display_name: "Execution Data",
    version: &[1],
    group: &["transform"],
    description: "Emit metadata about the current execution",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[],
};

#[async_trait]
impl Node for ExecutionDataNode {
    fn metadata(&self) -> &'static NodeMetadata { &META }

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let workflow_name = ctx.workflow_name.to_string();
        let execution_id = ctx.execution_id.to_string();
        let items_in = if ctx.input.is_empty() { vec![NodeItem::default()] } else { ctx.input.clone() };
        let mut out = Vec::with_capacity(items_in.len());
        for (idx, item) in items_in.into_iter().enumerate() {
            let mut new_json = if item.json.is_object() { item.json.clone() } else { json!({}) };
            new_json.as_object_mut().unwrap().insert("__execution".into(), json!({
                "workflow_name": workflow_name,
                "execution_id": execution_id,
                "item_index": idx,
                "node_name": ctx.node_def.name,
            }));
            out.push(NodeItem { json: new_json, ..item });
        }
        Ok(vec![out])
    }
}

inventory::submit! { NodeFactory::new("execution_data", || Arc::new(ExecutionDataNode)) }
