// 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)
//
// `trello` — get/create cards via the Trello REST API.
// Credential: trello = { api_key, 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::Value;
use std::sync::Arc;

pub struct TrelloNode;

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

#[async_trait]
impl Node for TrelloNode {
    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("trello.api_key".into()))?
            .to_string();
        let token = ctx.credential_field("api_token")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("trello.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.trello.com".to_string());
        let operation = ctx.node_def.parameters.get("operation")
            .and_then(|v| v.as_str()).unwrap_or("get_card").to_string();

        let auth = format!("key={}&token={}", api_key, token);
        let (method, url): (&str, String) = match operation.as_str() {
            "get_card" => {
                let id = ctx.param_str("card_id")?;
                ("GET", format!("{}/1/cards/{}?{}", base_url, id, auth))
            }
            "create_card" => {
                let list_id = ctx.param_str("list_id")?;
                let name = ctx.param_str("name")?;
                let desc = ctx.param_opt_str("desc").unwrap_or_default();
                ("POST", format!("{}/1/cards?idList={}&name={}&desc={}&{}",
                    base_url, list_id,
                    urlencode(&name), urlencode(&desc), auth))
            }
            "list_board_cards" => {
                let board_id = ctx.param_str("board_id")?;
                ("GET", format!("{}/1/boards/{}/cards?{}", base_url, board_id, auth))
            }
            other => return Err(NodeError::Other(format!("trello: unknown operation `{}`", other))),
        };

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

fn urlencode(s: &str) -> String {
    s.bytes().flat_map(|b| {
        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') { vec![b as char] }
        else { format!("%{:02X}", b).chars().collect() }
    }).collect()
}

inventory::submit! { NodeFactory::new("trello", || Arc::new(TrelloNode)) }
