// 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)
//
// `discord` — post a message via a Discord webhook URL.
// Credential: discord = { webhook_url = "https://discord.com/api/webhooks/..." }

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

static META: NodeMetadata = NodeMetadata {
    name: "discord",
    display_name: "Discord",
    version: &[1, 2],
    group: &["output"],
    description: "Send messages to a Discord channel via webhook URL",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[CredentialRef { name: "discord", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let webhook_url = ctx.credential_field("webhook_url")?
            .as_str()
            .ok_or_else(|| NodeError::MissingCredential("discord.webhook_url".into()))?
            .to_string();
        let content = ctx.param_str("content")?;
        let username = ctx.param_opt_str("username");

        let mut body = json!({ "content": content });
        if let Some(u) = username {
            body.as_object_mut().unwrap().insert("username".into(), Value::String(u));
        }

        let resp = reqwest::Client::new()
            .post(&webhook_url)
            .json(&body)
            .send().await
            .map_err(|e| NodeError::Http(format!("discord: {}", e)))?;
        let status = resp.status();
        // Discord webhook returns 204 No Content on success (or 200 with body if `?wait=true`).
        if !status.is_success() {
            let txt = resp.text().await.unwrap_or_default();
            return Err(NodeError::Http(format!("discord {}: {}", status, txt)));
        }
        let parsed: Value = resp.json::<Value>().await.unwrap_or(Value::Null);
        Ok(vec![vec![NodeItem {
            json: json!({ "status": status.as_u16(), "raw": parsed }),
            ..Default::default()
        }]])
    }
}

inventory::submit! { NodeFactory::new("discord", || Arc::new(DiscordNode)) }
