// 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)
//
// `set` — write fields onto each input item. Mirrors n8n's Set node.

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

pub struct SetNode;

static META: NodeMetadata = NodeMetadata {
    name: "set",
    display_name: "Set",
    version: &[1, 2],
    group: &["transform"],
    description: "Sets the value of one or more fields on incoming items",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let fields = ctx.param_value("fields").unwrap_or(Value::Object(Default::default()));
        let keep_only = ctx.node_def.parameters.get("keep_only_set")
            .and_then(|v| v.as_bool()).unwrap_or(false);

        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 item in items_in {
            let mut new_json = if keep_only || item.json.is_null() {
                Value::Object(Default::default())
            } else {
                item.json.clone()
            };
            if !new_json.is_object() {
                new_json = Value::Object(Default::default());
            }
            if let Value::Object(obj) = &fields {
                let target = new_json.as_object_mut().unwrap();
                for (k, v) in obj {
                    target.insert(k.clone(), v.clone());
                }
            }
            out.push(NodeItem { json: new_json, ..item });
        }
        Ok(vec![out])
    }
}

inventory::submit! { NodeFactory::new("set", || Arc::new(SetNode)) }
