// 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)
//
// `telegram` — send messages via the Telegram Bot API.
// Param names match n8n exactly (resource, operation, chatId, text).
// Credential `telegramApi`: { accessToken, baseUrl? = "https://api.telegram.org" }.

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

static META: NodeMetadata = NodeMetadata {
    name: "telegram",
    display_name: "Telegram",
    version: &[1, 2],
    group: &["output"],
    description: "Send messages, photos, etc. via the Telegram Bot API",
    inputs: 1,
    outputs: 1,
    properties: &[
        PropertyDef { name: "resource", display_name: "Resource", kind: PropertyKind::Options, required: true, default: Some("message") },
        PropertyDef { name: "operation", display_name: "Operation", kind: PropertyKind::Options, required: true, default: Some("sendMessage") },
        PropertyDef { name: "chatId", display_name: "Chat ID", kind: PropertyKind::String, required: true, default: None },
        PropertyDef { name: "text", display_name: "Text", kind: PropertyKind::String, required: false, default: None },
    ],
    credentials: &[CredentialRef { name: "telegramApi", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let token = ctx.credential_field("accessToken")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("telegramApi.accessToken".into()))?
            .to_string();
        let base_url = ctx.credential_field("baseUrl").ok()
            .and_then(|v| v.as_str().map(|s| s.trim_end_matches('/').to_string()))
            .unwrap_or_else(|| "https://api.telegram.org".to_string());
        let operation = ctx.node_def.parameters.get("operation")
            .and_then(|v| v.as_str()).unwrap_or("sendMessage").to_string();
        let chat_id = ctx.param_str("chatId")?;

        let (path, body): (&str, Value) = match operation.as_str() {
            "sendMessage" => {
                let text = ctx.param_str("text")?;
                ("sendMessage", json!({ "chat_id": chat_id, "text": text }))
            }
            "deleteMessage" => {
                let message_id = ctx.param_str("messageId")?;
                ("deleteMessage", json!({ "chat_id": chat_id, "message_id": message_id }))
            }
            other => return Err(NodeError::Other(format!("telegram: unknown operation `{}`", other))),
        };

        let resp = reqwest::Client::new()
            .post(format!("{}/bot{}/{}", base_url, token, path))
            .json(&body)
            .send().await.map_err(|e| NodeError::Http(format!("telegram: {}", e)))?;
        let status = resp.status();
        let parsed: Value = resp.json().await.unwrap_or(Value::Null);
        if !status.is_success() {
            return Err(NodeError::Http(format!("telegram {}: {}", status, parsed)));
        }
        Ok(vec![vec![NodeItem { json: parsed, ..Default::default() }]])
    }
}

inventory::submit! { NodeFactory::new("telegram", || Arc::new(TelegramNode)) }
