// 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)
//
// `influxdb` — Flux query against InfluxDB v2.
// Credential: influxdb = { base_url, token, 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;
use std::sync::Arc;

pub struct InfluxDbNode;

static META: NodeMetadata = NodeMetadata {
    name: "influxdb",
    display_name: "InfluxDB",
    version: &[1],
    group: &["database"],
    description: "Run Flux queries against an InfluxDB v2 cluster",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[CredentialRef { name: "influxdb", required: true }],
};

#[async_trait]
impl Node for InfluxDbNode {
    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("influxdb.base_url".into()))?
            .trim_end_matches('/').to_string();
        let token = ctx.credential_field("token")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("influxdb.token".into()))?
            .to_string();
        let org = ctx.credential_field("org")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("influxdb.org".into()))?
            .to_string();
        let query = ctx.param_str("query")?;

        let resp = reqwest::Client::new()
            .post(format!("{}/api/v2/query?org={}", base_url, org))
            .header("Authorization", format!("Token {}", token))
            .header("Content-Type", "application/json")
            .header("Accept", "application/csv")
            .json(&json!({ "query": query, "type": "flux" }))
            .send().await.map_err(|e| NodeError::Http(format!("influxdb: {}", e)))?;
        let status = resp.status();
        let body = resp.text().await.unwrap_or_default();
        if !status.is_success() {
            return Err(NodeError::Http(format!("influxdb {}: {}", status, body)));
        }
        Ok(vec![vec![NodeItem {
            json: json!({ "csv": body, "format": "annotated-csv" }),
            ..Default::default()
        }]])
    }
}

inventory::submit! { NodeFactory::new("influxdb", || Arc::new(InfluxDbNode)) }
