// 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)
//
// `grafana` — list dashboards / data sources via Grafana HTTP API.
// Credential: grafana = { base_url, api_key }

use async_trait::async_trait;
use crate::core::error::NodeError;
use crate::core::types::*;
use crate::engine::{ExecuteCtx, Node, NodeFactory};
use serde_json::Value;
use std::sync::Arc;

pub struct GrafanaNode;

static META: NodeMetadata = NodeMetadata {
    name: "grafana",
    display_name: "Grafana",
    version: &[1],
    group: &["output"],
    description: "Query Grafana dashboards, data sources, and alerts",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[CredentialRef { name: "grafana", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let base_url = ctx.credential_field("base_url")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("grafana.base_url".into()))?
            .trim_end_matches('/').to_string();
        let api_key = ctx.credential_field("api_key")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("grafana.api_key".into()))?
            .to_string();
        let operation = ctx.node_def.parameters.get("operation")
            .and_then(|v| v.as_str()).unwrap_or("search_dashboards").to_string();

        let url = match operation.as_str() {
            "search_dashboards" => format!("{}/api/search?type=dash-db", base_url),
            "list_datasources" => format!("{}/api/datasources", base_url),
            "list_alerts" => format!("{}/api/alerts", base_url),
            "get_dashboard" => {
                let uid = ctx.param_str("dashboard_uid")?;
                format!("{}/api/dashboards/uid/{}", base_url, uid)
            }
            other => return Err(NodeError::Other(format!("grafana: unknown operation `{}`", other))),
        };

        let resp = reqwest::Client::new().get(&url).bearer_auth(&api_key)
            .send().await.map_err(|e| NodeError::Http(format!("grafana: {}", e)))?;
        let status = resp.status();
        let parsed: Value = resp.json().await.unwrap_or(Value::Null);
        if !status.is_success() {
            return Err(NodeError::Http(format!("grafana {}: {}", status, parsed)));
        }
        Ok(vec![vec![NodeItem { json: parsed, ..Default::default() }]])
    }
}

inventory::submit! { NodeFactory::new("grafana", || Arc::new(GrafanaNode)) }
