// 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)
//
// `slack` — post a message to a Slack channel via the Web API.
// Credential: slack = { token = "xoxb-..." }
// Operations: post_message (default), update_message.

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

static META: NodeMetadata = NodeMetadata {
    name: "slack",
    display_name: "Slack",
    version: &[1, 2],
    group: &["output"],
    description: "Send messages to Slack channels",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[CredentialRef { name: "slack", required: true }],
};

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

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

        let endpoint = match operation.as_str() {
            "post_message" => format!("{}/api/chat.postMessage", base_url),
            "update_message" => format!("{}/api/chat.update", base_url),
            other => return Err(NodeError::Other(format!("slack: unknown operation `{}`", other))),
        };

        let mut body = json!({ "channel": channel, "text": text });
        if operation == "update_message" {
            let ts = ctx.param_str("ts")?;
            body.as_object_mut().unwrap().insert("ts".to_string(), Value::String(ts));
        }

        let client = reqwest::Client::new();
        let resp = client.post(&endpoint)
            .bearer_auth(&token)
            .json(&body)
            .send().await
            .map_err(|e| NodeError::Http(format!("slack: {}", e)))?;
        let parsed: Value = resp.json().await
            .map_err(|e| NodeError::Http(format!("slack response: {}", e)))?;
        if parsed.get("ok").and_then(|v| v.as_bool()) != Some(true) {
            let err = parsed.get("error").and_then(|v| v.as_str()).unwrap_or("unknown");
            return Err(NodeError::Other(format!("slack api error: {}", err)));
        }
        Ok(vec![vec![NodeItem { json: parsed, ..Default::default() }]])
    }
}

inventory::submit! { NodeFactory::new("slack", || Arc::new(SlackNode)) }
