// 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)
//
// `uuid` — generate UUIDs (v4 by default) and attach to 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 UuidNode;

static META: NodeMetadata = NodeMetadata {
    name: "uuid",
    display_name: "UUID",
    version: &[1],
    group: &["transform"],
    description: "Generate a UUID per item and attach it to a configurable field",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let field = ctx.node_def.parameters.get("output_field")
            .and_then(|v| v.as_str()).unwrap_or("id").to_string();
        let count = ctx.node_def.parameters.get("count_per_item")
            .and_then(|v| v.as_u64()).unwrap_or(1) as usize;

        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 item.json.is_object() { item.json.clone() } else { Value::Object(Default::default()) };
            let value = if count == 1 {
                Value::String(uuid::Uuid::new_v4().to_string())
            } else {
                Value::Array((0..count).map(|_| Value::String(uuid::Uuid::new_v4().to_string())).collect())
            };
            new_json.as_object_mut().unwrap().insert(field.clone(), value);
            out.push(NodeItem { json: new_json, ..item });
        }
        Ok(vec![out])
    }
}

inventory::submit! { NodeFactory::new("uuid", || Arc::new(UuidNode)) }
