// 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)
//
// `graphql` — POST a GraphQL query to an endpoint. Optional credential:
// graphql = { token = "..." } adds Authorization: Bearer.

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

static META: NodeMetadata = NodeMetadata {
    name: "graphql",
    display_name: "GraphQL",
    version: &[1],
    group: &["transform"],
    description: "Send a GraphQL query to an endpoint",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let endpoint = ctx.param_str("endpoint")?;
        let query = ctx.param_str("query")?;
        let variables = ctx.node_def.parameters.get("variables").cloned()
            .unwrap_or(Value::Object(Default::default()));
        let token = ctx.credential_field("token").ok()
            .and_then(|v| v.as_str().map(|s| s.to_string()));

        let body = json!({ "query": query, "variables": variables });
        let mut req = reqwest::Client::new()
            .post(&endpoint)
            .json(&body);
        if let Some(t) = token { req = req.bearer_auth(t); }
        let resp = req.send().await.map_err(|e| NodeError::Http(format!("graphql: {}", e)))?;
        let status = resp.status();
        let parsed: Value = resp.json().await.map_err(|e| NodeError::Http(format!("graphql response: {}", e)))?;
        if !status.is_success() {
            return Err(NodeError::Http(format!("graphql {}: {}", status, parsed)));
        }
        if let Some(errors) = parsed.get("errors").and_then(|v| v.as_array()) {
            if !errors.is_empty() {
                return Err(NodeError::Other(format!("graphql errors: {}", Value::Array(errors.clone()))));
            }
        }
        Ok(vec![vec![NodeItem { json: parsed, ..Default::default() }]])
    }
}

inventory::submit! { NodeFactory::new("graphql", || Arc::new(GraphQlNode)) }
