// 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)
//
// `linear` — issues via Linear's GraphQL API.
// Credential: linear = { api_key = "lin_api_..." }

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

static META: NodeMetadata = NodeMetadata {
    name: "linear",
    display_name: "Linear",
    version: &[1],
    group: &["output"],
    description: "Query and mutate Linear issues via GraphQL",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[CredentialRef { name: "linear", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let api_key = ctx.credential_field("api_key")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("linear.api_key".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.linear.app".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!("{}/graphql", base_url))
            .header("Authorization", &api_key)
            .json(&json!({ "query": query, "variables": variables }))
            .send().await.map_err(|e| NodeError::Http(format!("linear: {}", e)))?;
        let status = resp.status();
        let parsed: Value = resp.json().await.unwrap_or(Value::Null);
        if !status.is_success() {
            return Err(NodeError::Http(format!("linear {}: {}", status, parsed)));
        }
        Ok(vec![vec![NodeItem { json: parsed, ..Default::default() }]])
    }
}

inventory::submit! { NodeFactory::new("linear", || Arc::new(LinearNode)) }
