// 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)
//
// `mqtt` — publish messages to an MQTT broker.
// Param names: topic, message, sendInputData, qos, retain.
// Credential `mqtt`: { protocol, host, port, username?, password?, clean,
// clientId, ssl?, passwordless }.

use async_trait::async_trait;
use crate::core::error::NodeError;
use crate::core::types::*;
use crate::engine::{ExecuteCtx, Node, NodeFactory};
use rumqttc::{AsyncClient, MqttOptions, QoS};
use serde_json::json;
use std::sync::Arc;
use std::time::Duration;

pub struct MqttNode;

static META: NodeMetadata = NodeMetadata {
    name: "mqtt",
    display_name: "MQTT",
    version: &[1],
    group: &["output"],
    description: "Publish messages to an MQTT broker",
    inputs: 1,
    outputs: 1,
    properties: &[
        PropertyDef { name: "topic", display_name: "Topic", kind: PropertyKind::String, required: true, default: None },
        PropertyDef { name: "sendInputData", display_name: "Send Input Data", kind: PropertyKind::Boolean, required: false, default: Some("true") },
        PropertyDef { name: "message", display_name: "Message", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "qos", display_name: "QoS", kind: PropertyKind::Number, required: false, default: Some("0") },
        PropertyDef { name: "retain", display_name: "Retain", kind: PropertyKind::Boolean, required: false, default: Some("false") },
    ],
    credentials: &[CredentialRef { name: "mqtt", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let host = ctx.credential_field("host")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("mqtt.host".into()))?
            .to_string();
        let port = ctx.credential_field("port").ok()
            .and_then(|v| v.as_u64()).map(|n| n as u16).unwrap_or(1883);
        let username = ctx.credential_field("username").ok()
            .and_then(|v| v.as_str().map(|s| s.to_string()));
        let password = ctx.credential_field("password").ok()
            .and_then(|v| v.as_str().map(|s| s.to_string()));
        let client_id = ctx.credential_field("clientId").ok()
            .and_then(|v| v.as_str().map(|s| s.to_string()))
            .unwrap_or_else(|| format!("r8r-{}", std::process::id()));
        let clean = ctx.credential_field("clean").ok()
            .and_then(|v| v.as_bool()).unwrap_or(true);

        let topic = ctx.param_str("topic")?;
        let qos_raw = ctx.node_def.parameters.get("qos")
            .and_then(|v| v.as_u64()).unwrap_or(0);
        let qos = match qos_raw { 1 => QoS::AtLeastOnce, 2 => QoS::ExactlyOnce, _ => QoS::AtMostOnce };
        let retain = ctx.node_def.parameters.get("retain")
            .and_then(|v| v.as_bool()).unwrap_or(false);
        let send_input = ctx.node_def.parameters.get("sendInputData")
            .and_then(|v| v.as_bool()).unwrap_or(true);

        let mut opts = MqttOptions::new(client_id, &host, port);
        opts.set_clean_session(clean);
        opts.set_keep_alive(Duration::from_secs(30));
        if let (Some(u), Some(p)) = (username, password) {
            opts.set_credentials(u, p);
        }
        let (client, mut eventloop) = AsyncClient::new(opts, 16);

        // Spawn the eventloop pump so the publish actually sends.
        let pump = tokio::spawn(async move {
            for _ in 0..50 {
                if let Err(e) = eventloop.poll().await {
                    tracing::warn!("mqtt eventloop: {}", e);
                    break;
                }
            }
        });

        let mut sent = 0;
        let items_in = if ctx.input.is_empty() { vec![NodeItem::default()] } else { ctx.input.clone() };
        for item in &items_in {
            let payload: Vec<u8> = if send_input {
                serde_json::to_vec(&item.json).unwrap_or_default()
            } else {
                ctx.param_opt_str("message").unwrap_or_default().into_bytes()
            };
            client.publish(&topic, qos, retain, payload).await
                .map_err(|e| NodeError::Other(format!("mqtt publish: {}", e)))?;
            sent += 1;
        }

        // Give the eventloop a moment to flush, then drop.
        tokio::time::sleep(Duration::from_millis(150)).await;
        drop(client);
        let _ = tokio::time::timeout(Duration::from_millis(200), pump).await;

        Ok(vec![vec![NodeItem {
            json: json!({ "topic": topic, "messages_sent": sent, "qos": qos_raw, "retain": retain }),
            ..Default::default()
        }]])
    }
}

inventory::submit! { NodeFactory::new("mqtt", || Arc::new(MqttNode)) }
