// 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)
//
// `elasticsearch` — search/index/get against an Elasticsearch endpoint.
// Credential: elasticsearch = { base_url, username?, password?, 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 ElasticsearchNode;

static META: NodeMetadata = NodeMetadata {
    name: "elasticsearch",
    display_name: "Elasticsearch",
    version: &[1],
    group: &["database"],
    description: "Search, index, or fetch documents from Elasticsearch",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[CredentialRef { name: "elasticsearch", required: true }],
};

#[async_trait]
impl Node for ElasticsearchNode {
    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("elasticsearch.base_url".into()))?
            .trim_end_matches('/').to_string();
        let api_key = ctx.credential_field("api_key").ok().and_then(|v| v.as_str().map(|s| s.to_string()));
        let username = ctx.credential_field("username").ok().and_then(|v| v.as_str().map(|s| s.to_string()));
        let password = ctx.credential_field("password").ok().and_then(|v| v.as_str().map(|s| s.to_string()));
        let operation = ctx.node_def.parameters.get("operation")
            .and_then(|v| v.as_str()).unwrap_or("search").to_string();
        let index = ctx.param_str("index")?;

        let (method, url, body): (&str, String, Option<Value>) = match operation.as_str() {
            "search" => {
                let query = ctx.node_def.parameters.get("query").cloned()
                    .unwrap_or(serde_json::json!({"query": {"match_all": {}}}));
                ("POST", format!("{}/{}/_search", base_url, index), Some(query))
            }
            "index" => {
                let document = ctx.node_def.parameters.get("document").cloned()
                    .ok_or_else(|| NodeError::MissingParameter("document".into()))?;
                ("POST", format!("{}/{}/_doc", base_url, index), Some(document))
            }
            "get" => {
                let id = ctx.param_str("id")?;
                ("GET", format!("{}/{}/_doc/{}", base_url, index, id), None)
            }
            other => return Err(NodeError::Other(format!("elasticsearch: unknown operation `{}`", other))),
        };

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

inventory::submit! { NodeFactory::new("elasticsearch", || Arc::new(ElasticsearchNode)) }
