// 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)
//
// `asana` — task CRUD via the Asana REST API.
// Credential: asana = { access_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 AsanaNode;

static META: NodeMetadata = NodeMetadata {
    name: "asana",
    display_name: "Asana",
    version: &[1],
    group: &["output"],
    description: "Read or create Asana tasks",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[CredentialRef { name: "asana", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let token = ctx.credential_field("access_token")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("asana.access_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://app.asana.com".to_string());
        let operation = ctx.node_def.parameters.get("operation")
            .and_then(|v| v.as_str()).unwrap_or("get_task").to_string();

        let (method, url, body): (&str, String, Option<Value>) = match operation.as_str() {
            "get_task" => {
                let id = ctx.param_str("task_gid")?;
                ("GET", format!("{}/api/1.0/tasks/{}", base_url, id), None)
            }
            "create_task" => {
                let workspace = ctx.param_str("workspace")?;
                let name = ctx.param_str("name")?;
                let notes = ctx.param_opt_str("notes").unwrap_or_default();
                ("POST", format!("{}/api/1.0/tasks", base_url),
                 Some(json!({ "data": { "workspace": workspace, "name": name, "notes": notes } })))
            }
            other => return Err(NodeError::Other(format!("asana: unknown operation `{}`", other))),
        };

        let mut req = reqwest::Client::new().request(method.parse().unwrap(), &url).bearer_auth(&token);
        if let Some(b) = body { req = req.json(&b); }
        let resp = req.send().await.map_err(|e| NodeError::Http(format!("asana: {}", e)))?;
        let status = resp.status();
        let parsed: Value = resp.json().await.unwrap_or(Value::Null);
        if !status.is_success() {
            return Err(NodeError::Http(format!("asana {}: {}", status, parsed)));
        }
        Ok(vec![vec![NodeItem { json: parsed, ..Default::default() }]])
    }
}

inventory::submit! { NodeFactory::new("asana", || Arc::new(AsanaNode)) }
