// 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)
//
// `switch` — multi-output If. Routes each item to one of N outputs based on
// the value of a top-level key against a list of cases.

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

static META: NodeMetadata = NodeMetadata {
    name: "switch",
    display_name: "Switch",
    version: &[1, 2, 3],
    group: &["transform"],
    description: "Routes items to one of multiple outputs based on a value match",
    inputs: 1,
    outputs: 4,
    properties: &[],
    credentials: &[],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let key = ctx.node_def.parameters.get("key")
            .and_then(|v| v.as_str())
            .ok_or_else(|| NodeError::MissingParameter("key".into()))?
            .to_string();
        let cases = ctx.node_def.parameters.get("cases")
            .and_then(|v| v.as_array())
            .cloned()
            .unwrap_or_default();
        let outputs_count = META.outputs as usize;
        let default_output = ctx.node_def.parameters.get("default_output")
            .and_then(|v| v.as_u64())
            .map(|n| (n as usize).min(outputs_count - 1))
            .unwrap_or(outputs_count - 1);

        let mut buckets: Vec<Vec<NodeItem>> = (0..outputs_count).map(|_| Vec::new()).collect();

        for item in &ctx.input {
            let val = item.json.get(&key).cloned().unwrap_or(Value::Null);
            let mut routed = false;
            for case in &cases {
                let case_val = case.get("value").cloned().unwrap_or(Value::Null);
                if values_match(&val, &case_val) {
                    let out_idx = case.get("output_index")
                        .and_then(|v| v.as_u64())
                        .unwrap_or(0) as usize;
                    buckets[out_idx.min(outputs_count - 1)].push(item.clone());
                    routed = true;
                    break;
                }
            }
            if !routed {
                buckets[default_output].push(item.clone());
            }
        }
        Ok(buckets)
    }
}

fn values_match(a: &Value, b: &Value) -> bool {
    match (a, b) {
        (Value::Number(x), Value::Number(y)) => {
            x.as_f64().zip(y.as_f64()).map(|(p, q)| (p - q).abs() < f64::EPSILON).unwrap_or(false)
        }
        _ => a == b,
    }
}

inventory::submit! { NodeFactory::new("switch", || Arc::new(SwitchNode)) }
