// 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)
//
// `markdown` — convert Markdown to HTML via pulldown-cmark.

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

pub struct MarkdownNode;

static META: NodeMetadata = NodeMetadata {
    name: "markdown",
    display_name: "Markdown",
    version: &[1],
    group: &["transform"],
    description: "Convert Markdown to HTML",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let field = ctx.node_def.parameters.get("output_field")
            .and_then(|v| v.as_str())
            .unwrap_or("html").to_string();
        let mut opts = Options::empty();
        opts.insert(Options::ENABLE_TABLES);
        opts.insert(Options::ENABLE_STRIKETHROUGH);
        opts.insert(Options::ENABLE_TASKLISTS);

        let items_in = if ctx.input.is_empty() { vec![NodeItem::default()] } else { ctx.input.clone() };
        let mut out = Vec::with_capacity(items_in.len());
        for item in items_in {
            let md = ctx.param_str("markdown").unwrap_or_default();
            let parser = Parser::new_ext(&md, opts);
            let mut html_out = String::new();
            html::push_html(&mut html_out, parser);
            let mut new_json = if item.json.is_object() { item.json.clone() } else { Value::Object(Default::default()) };
            new_json.as_object_mut().unwrap().insert(field.clone(), Value::String(html_out));
            out.push(NodeItem { json: new_json, ..item });
        }
        Ok(vec![out])
    }
}

inventory::submit! { NodeFactory::new("markdown", || Arc::new(MarkdownNode)) }
