// 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)
//
// `rename_keys` — rename top-level fields on each item.

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 RenameKeysNode;

static META: NodeMetadata = NodeMetadata {
    name: "rename_keys",
    display_name: "Rename Keys",
    version: &[1],
    group: &["transform"],
    description: "Rename top-level keys on each item",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let pairs: Vec<(String, String)> = ctx.node_def.parameters.get("pairs")
            .and_then(|v| v.as_array())
            .map(|arr| arr.iter().filter_map(|entry| {
                let from = entry.get("from")?.as_str()?.to_string();
                let to = entry.get("to")?.as_str()?.to_string();
                Some((from, to))
            }).collect())
            .unwrap_or_default();
        if pairs.is_empty() {
            return Err(NodeError::MissingParameter("pairs".into()));
        }

        let mut out = Vec::with_capacity(ctx.input.len());
        for item in &ctx.input {
            let mut new_json = item.json.clone();
            if let Value::Object(obj) = &mut new_json {
                for (from, to) in &pairs {
                    if let Some(v) = obj.remove(from) {
                        obj.insert(to.clone(), v);
                    }
                }
            }
            out.push(NodeItem { json: new_json, ..item.clone() });
        }
        Ok(vec![out])
    }
}

inventory::submit! { NodeFactory::new("rename_keys", || Arc::new(RenameKeysNode)) }
