// 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)
//
// `n8n_api` — call the n8n REST API. Useful for migrating workflows
// from a running n8n instance into r8r. Note: this hits a
// real n8n's `/api/v1/workflows` endpoint with an X-N8N-API-KEY header.
// Credential: n8n_api = { base_url, api_key }

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

static META: NodeMetadata = NodeMetadata {
    name: "n8n_api",
    display_name: "n8n (Migration)",
    version: &[1],
    group: &["output"],
    description: "Call a running n8n instance's REST API (useful for migration)",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[CredentialRef { name: "n8n_api", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let base_url = ctx.credential_field("base_url")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("n8n_api.base_url".into()))?
            .trim_end_matches('/').to_string();
        let api_key = ctx.credential_field("api_key")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("n8n_api.api_key".into()))?
            .to_string();
        let operation = ctx.node_def.parameters.get("operation")
            .and_then(|v| v.as_str()).unwrap_or("list_workflows").to_string();

        let url = match operation.as_str() {
            "list_workflows" => format!("{}/api/v1/workflows", base_url),
            "get_workflow" => {
                let id = ctx.param_str("workflow_id")?;
                format!("{}/api/v1/workflows/{}", base_url, id)
            }
            "list_executions" => format!("{}/api/v1/executions", base_url),
            other => return Err(NodeError::Other(format!("n8n_api: unknown operation `{}`", other))),
        };

        let resp = reqwest::Client::new().get(&url)
            .header("X-N8N-API-KEY", &api_key)
            .send().await.map_err(|e| NodeError::Http(format!("n8n_api: {}", e)))?;
        let status = resp.status();
        let parsed: Value = resp.json().await.unwrap_or(Value::Null);
        if !status.is_success() {
            return Err(NodeError::Http(format!("n8n_api {}: {}", status, parsed)));
        }
        Ok(vec![vec![NodeItem { json: parsed, ..Default::default() }]])
    }
}

inventory::submit! { NodeFactory::new("n8n_api", || Arc::new(N8nApiNode)) }
