// 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)
//
// `cortex` — analyzers + responders via TheHive Cortex REST.
// Param names: resource (analyzer/job/responder), operation, jobId,
// analyzerId, entityType, observableValue, responder.
// Credential `cortexApi`: { cortexApiKey, host }.

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

static META: NodeMetadata = NodeMetadata {
    name: "cortex",
    display_name: "Cortex",
    version: &[1],
    group: &["output"],
    description: "Run TheHive Cortex analyzers and responders",
    inputs: 1,
    outputs: 1,
    properties: &[
        PropertyDef { name: "resource", display_name: "Resource", kind: PropertyKind::Options, required: true, default: Some("analyzer") },
        PropertyDef { name: "operation", display_name: "Operation", kind: PropertyKind::Options, required: true, default: Some("getAll") },
        PropertyDef { name: "jobId", display_name: "Job ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "analyzerId", display_name: "Analyzer ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "entityType", display_name: "Entity Type", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "observableValue", display_name: "Observable Value", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "responder", display_name: "Responder", kind: PropertyKind::String, required: false, default: None },
    ],
    credentials: &[CredentialRef { name: "cortexApi", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let api_key = ctx.credential_field("cortexApiKey")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("cortexApi.cortexApiKey".into()))?
            .to_string();
        let host = ctx.credential_field("host")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("cortexApi.host".into()))?
            .trim_end_matches('/').to_string();
        let resource = ctx.param_opt_str("resource").unwrap_or_else(|| "analyzer".into());
        let operation = ctx.param_opt_str("operation").unwrap_or_else(|| "getAll".into());

        let (method, url, body): (&str, String, Option<Value>) = match (resource.as_str(), operation.as_str()) {
            ("analyzer", "getAll") => ("GET", format!("{}/api/analyzer", host), None),
            ("analyzer", "execute") => {
                let id = ctx.param_str("analyzerId")?;
                let entity_type = ctx.param_str("entityType")?;
                let value = ctx.param_str("observableValue")?;
                ("POST", format!("{}/api/analyzer/{}/run", host, id),
                 Some(json!({ "data": value, "dataType": entity_type, "tlp": 1 })))
            }
            ("job", "get") => {
                let id = ctx.param_str("jobId")?;
                ("GET", format!("{}/api/job/{}", host, id), None)
            }
            ("job", "report") => {
                let id = ctx.param_str("jobId")?;
                ("GET", format!("{}/api/job/{}/report", host, id), None)
            }
            ("responder", "execute") => {
                let responder = ctx.param_str("responder")?;
                let entity_type = ctx.param_str("entityType")?;
                ("POST", format!("{}/api/responder/{}/run", host, responder),
                 Some(json!({ "dataType": entity_type })))
            }
            (r, o) => return Err(NodeError::Other(format!("cortex: {}.{} not implemented", r, o))),
        };

        let mut req = reqwest::Client::new().request(method.parse().unwrap(), &url).bearer_auth(&api_key);
        if let Some(b) = body { req = req.json(&b); }
        let resp = req.send().await.map_err(|e| NodeError::Http(format!("cortex: {}", e)))?;
        let status = resp.status();
        let parsed: Value = resp.json().await.unwrap_or(Value::Null);
        if !status.is_success() {
            return Err(NodeError::Http(format!("cortex {}: {}", status, parsed)));
        }
        Ok(vec![vec![NodeItem { json: parsed, ..Default::default() }]])
    }
}

inventory::submit! { NodeFactory::new("cortex", || Arc::new(CortexNode)) }
