// 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)
//
// `splunk` — search jobs + log ingestion via Splunk REST.
// Param names: resource, operation, search, returnAll.
// Credential `splunkApi`: { authToken, baseUrl, allowUnauthorizedCerts }.

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

static META: NodeMetadata = NodeMetadata {
    name: "splunk",
    display_name: "Splunk",
    version: &[1, 2],
    group: &["output"],
    description: "Run Splunk searches and ingest events via HEC",
    inputs: 1,
    outputs: 1,
    properties: &[
        PropertyDef { name: "resource", display_name: "Resource", kind: PropertyKind::Options, required: true, default: Some("searchJob") },
        PropertyDef { name: "operation", display_name: "Operation", kind: PropertyKind::Options, required: true, default: Some("create") },
        PropertyDef { name: "search", display_name: "Search Query", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "event", display_name: "Event (HEC)", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "sourceType", display_name: "Source Type", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "sid", display_name: "Search Job SID", kind: PropertyKind::String, required: false, default: None },
    ],
    credentials: &[CredentialRef { name: "splunkApi", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let token = ctx.credential_field("authToken")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("splunkApi.authToken".into()))?
            .to_string();
        let base_url = ctx.credential_field("baseUrl")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("splunkApi.baseUrl".into()))?
            .trim_end_matches('/').to_string();
        let allow_unauth = ctx.credential_field("allowUnauthorizedCerts").ok()
            .and_then(|v| v.as_bool()).unwrap_or(false);
        let resource = ctx.param_opt_str("resource").unwrap_or_else(|| "searchJob".into());
        let operation = ctx.param_opt_str("operation").unwrap_or_else(|| "create".into());

        let client = reqwest::Client::builder()
            .danger_accept_invalid_certs(allow_unauth)
            .build()
            .map_err(|e| NodeError::Http(format!("splunk: client: {}", e)))?;

        let (method, url, body): (&str, String, Option<Value>) = match (resource.as_str(), operation.as_str()) {
            ("searchJob", "create") => {
                let search = ctx.param_str("search")?;
                ("POST", format!("{}/services/search/jobs?output_mode=json", base_url),
                 Some(json!({ "search": search })))
            }
            ("searchJob", "get") => {
                let sid = ctx.param_str("sid")?;
                ("GET", format!("{}/services/search/jobs/{}?output_mode=json", base_url, sid), None)
            }
            ("searchJob", "getResults") => {
                let sid = ctx.param_str("sid")?;
                ("GET", format!("{}/services/search/jobs/{}/results?output_mode=json", base_url, sid), None)
            }
            ("event", "create") => {
                let event = ctx.param_str("event")?;
                let source_type = ctx.param_opt_str("sourceType");
                let mut payload = json!({ "event": event });
                if let Some(st) = source_type {
                    payload.as_object_mut().unwrap().insert("sourcetype".into(), Value::String(st));
                }
                ("POST", format!("{}/services/collector", base_url), Some(payload))
            }
            (r, o) => return Err(NodeError::Other(format!("splunk: {}.{} not implemented", r, o))),
        };

        let mut req = client.request(method.parse().unwrap(), &url)
            .header("Authorization", format!("Splunk {}", token));
        // For HEC the format is "Splunk <token>"; for REST API it's the same.
        if let Some(b) = body {
            // searchJob create takes form-urlencoded, event ingestion takes JSON
            if matches!(operation.as_str(), "create") && resource == "searchJob" {
                let search_str = b.get("search").and_then(|v| v.as_str()).unwrap_or("");
                req = req.form(&[("search", search_str)]);
            } else {
                req = req.json(&b);
            }
        }
        let resp = req.send().await.map_err(|e| NodeError::Http(format!("splunk: {}", e)))?;
        let status = resp.status();
        let parsed: Value = resp.json().await.unwrap_or(Value::Null);
        if !status.is_success() {
            return Err(NodeError::Http(format!("splunk {}: {}", status, parsed)));
        }
        Ok(vec![vec![NodeItem { json: parsed, ..Default::default() }]])
    }
}

inventory::submit! { NodeFactory::new("splunk", || Arc::new(SplunkNode)) }
