// 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)
//
// `datadog` — submit metrics, events, logs via the Datadog v1/v2 API.
// Param names: resource, operation, title, text, tags, alertType, metric.
// Credential `datadogApi`: { apiKey, appKey, site? = "datadoghq.com" }.

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

static META: NodeMetadata = NodeMetadata {
    name: "datadog",
    display_name: "Datadog",
    version: &[1],
    group: &["output"],
    description: "Submit metrics, events, and logs to Datadog",
    inputs: 1,
    outputs: 1,
    properties: &[
        PropertyDef { name: "resource", display_name: "Resource", kind: PropertyKind::Options, required: true, default: Some("event") },
        PropertyDef { name: "operation", display_name: "Operation", kind: PropertyKind::Options, required: true, default: Some("create") },
        PropertyDef { name: "title", display_name: "Title", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "text", display_name: "Text", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "alertType", display_name: "Alert Type", kind: PropertyKind::Options, required: false, default: Some("info") },
        PropertyDef { name: "tags", display_name: "Tags", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "metric", display_name: "Metric Name", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "value", display_name: "Metric Value", kind: PropertyKind::Number, required: false, default: None },
        PropertyDef { name: "message", display_name: "Log Message", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "service", display_name: "Service", kind: PropertyKind::String, required: false, default: None },
    ],
    credentials: &[CredentialRef { name: "datadogApi", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let api_key = ctx.credential_field("apiKey")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("datadogApi.apiKey".into()))?
            .to_string();
        let app_key = ctx.credential_field("appKey").ok()
            .and_then(|v| v.as_str().map(|s| s.to_string()));
        let site = ctx.credential_field("site").ok()
            .and_then(|v| v.as_str().map(|s| s.to_string()))
            .unwrap_or_else(|| "datadoghq.com".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(|| format!("https://api.{}", site));
        let resource = ctx.param_opt_str("resource").unwrap_or_else(|| "event".into());

        let tags: Vec<String> = ctx.param_opt_str("tags").map(|s|
            s.split(',').map(|t| t.trim().to_string()).filter(|t| !t.is_empty()).collect()
        ).unwrap_or_default();

        let (url, body): (String, Value) = match resource.as_str() {
            "event" => {
                let title = ctx.param_str("title")?;
                let text = ctx.param_str("text")?;
                let alert_type = ctx.param_opt_str("alertType").unwrap_or_else(|| "info".into());
                (format!("{}/api/v1/events", base_url),
                 json!({ "title": title, "text": text, "alert_type": alert_type, "tags": tags }))
            }
            "metric" => {
                let metric = ctx.param_str("metric")?;
                let value = ctx.node_def.parameters.get("value").and_then(|v| v.as_f64()).unwrap_or(0.0);
                let now = chrono::Utc::now().timestamp();
                (format!("{}/api/v1/series", base_url),
                 json!({
                     "series": [{
                         "metric": metric,
                         "points": [[now, value]],
                         "type": "gauge",
                         "tags": tags,
                     }]
                 }))
            }
            "log" => {
                let message = ctx.param_str("message")?;
                let service = ctx.param_opt_str("service").unwrap_or_else(|| "r8r".into());
                let log_url = format!("https://http-intake.logs.{}/api/v2/logs", site);
                (log_url,
                 json!([{ "message": message, "service": service, "ddtags": tags.join(",") }]))
            }
            other => return Err(NodeError::Other(format!("datadog: unknown resource `{}`", other))),
        };

        let mut req = reqwest::Client::new().post(&url)
            .header("DD-API-KEY", &api_key);
        if let Some(ak) = app_key { req = req.header("DD-APPLICATION-KEY", ak); }
        let resp = req.json(&body).send().await
            .map_err(|e| NodeError::Http(format!("datadog: {}", e)))?;
        let status = resp.status();
        let parsed: Value = resp.json().await.unwrap_or(Value::Null);
        if !status.is_success() {
            return Err(NodeError::Http(format!("datadog {}: {}", status, parsed)));
        }
        Ok(vec![vec![NodeItem { json: parsed, ..Default::default() }]])
    }
}

inventory::submit! { NodeFactory::new("datadog", || Arc::new(DatadogNode)) }
