// 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)
//
// `monday` — boards/items via monday.com GraphQL API v2.
// Credential: monday = { api_token = "..." }

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

static META: NodeMetadata = NodeMetadata {
    name: "monday",
    display_name: "Monday.com",
    version: &[1],
    group: &["output"],
    description: "Query and mutate monday.com boards/items via GraphQL",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[CredentialRef { name: "monday", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let token = ctx.credential_field("api_token")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("monday.api_token".into()))?
            .to_string();
        let base_url = ctx.credential_field("base_url").ok()
            .and_then(|v| v.as_str().map(|s| s.trim_end_matches('/').to_string()))
            .unwrap_or_else(|| "https://api.monday.com".to_string());
        let query = ctx.param_str("query")?;
        let variables = ctx.node_def.parameters.get("variables").cloned()
            .unwrap_or(Value::Object(Default::default()));

        let resp = reqwest::Client::new()
            .post(format!("{}/v2", base_url))
            .header("Authorization", &token)
            .header("API-Version", "2024-01")
            .json(&json!({ "query": query, "variables": variables }))
            .send().await.map_err(|e| NodeError::Http(format!("monday: {}", e)))?;
        let status = resp.status();
        let parsed: Value = resp.json().await.unwrap_or(Value::Null);
        if !status.is_success() {
            return Err(NodeError::Http(format!("monday {}: {}", status, parsed)));
        }
        Ok(vec![vec![NodeItem { json: parsed, ..Default::default() }]])
    }
}

inventory::submit! { NodeFactory::new("monday", || Arc::new(MondayNode)) }
