// 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)
//
// `respond_to_webhook` — pairs with the `webhook` trigger. v0.1's webhook
// node already responds with "ok" inline before it returns; this node is
// the explicit-response variant: emits a JSON envelope describing the
// intended response shape so a future v0.2 deferred-response webhook can
// consume it.

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

pub struct RespondToWebhookNode;

static META: NodeMetadata = NodeMetadata {
    name: "respond_to_webhook",
    display_name: "Respond to Webhook",
    version: &[1],
    group: &["output"],
    description: "Mark this branch as the response for the upstream webhook trigger",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let status = ctx.node_def.parameters.get("status_code")
            .and_then(|v| v.as_u64()).unwrap_or(200);
        let body = ctx.node_def.parameters.get("body").cloned()
            .unwrap_or(Value::String("ok".into()));
        let headers = ctx.node_def.parameters.get("headers").cloned()
            .unwrap_or(Value::Object(Default::default()));
        Ok(vec![vec![NodeItem {
            json: json!({
                "__webhook_response": {
                    "status_code": status,
                    "body": body,
                    "headers": headers,
                }
            }),
            ..Default::default()
        }]])
    }
}

inventory::submit! { NodeFactory::new("respond_to_webhook", || Arc::new(RespondToWebhookNode)) }
