// 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)
//
// `bannerbear` — generate images from templates via Bannerbear v2 REST.
// Param names: resource (image), operation, templateId, modificationsUi,
// imageId.
// Credential `bannerbearApi`: { apiKey }.

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

static META: NodeMetadata = NodeMetadata {
    name: "bannerbear",
    display_name: "Bannerbear",
    version: &[1],
    group: &["output"],
    description: "Generate images from Bannerbear templates",
    inputs: 1,
    outputs: 1,
    properties: &[
        PropertyDef { name: "resource", display_name: "Resource", kind: PropertyKind::Options, required: true, default: Some("image") },
        PropertyDef { name: "operation", display_name: "Operation", kind: PropertyKind::Options, required: true, default: Some("create") },
        PropertyDef { name: "templateId", display_name: "Template ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "modificationsUi", display_name: "Modifications", kind: PropertyKind::Json, required: false, default: None },
        PropertyDef { name: "metadata", display_name: "Metadata", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "webhookUrl", display_name: "Webhook URL", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "imageId", display_name: "Image ID", kind: PropertyKind::String, required: false, default: None },
    ],
    credentials: &[CredentialRef { name: "bannerbearApi", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let api_key = ctx.credential_field("apiKey")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("bannerbearApi.apiKey".into()))?
            .to_string();
        let base_url = ctx.credential_field("base_url").ok()
            .and_then(|v| v.as_str().map(|s| s.trim_end_matches('/').to_string()))
            .unwrap_or_else(|| "https://api.bannerbear.com".to_string());
        let operation = ctx.param_opt_str("operation").unwrap_or_else(|| "create".into());

        let (method, url, body): (&str, String, Option<Value>) = match operation.as_str() {
            "create" => {
                let template = ctx.param_str("templateId")?;
                let mods = ctx.node_def.parameters.get("modificationsUi")
                    .and_then(|v| match v {
                        Value::Object(o) => o.get("modifications").cloned(),
                        _ => None,
                    })
                    .or_else(|| ctx.node_def.parameters.get("modificationsUi").cloned())
                    .unwrap_or(Value::Array(vec![]));
                let metadata = ctx.param_opt_str("metadata");
                let webhook = ctx.param_opt_str("webhookUrl");
                let mut payload = json!({
                    "template": template,
                    "modifications": mods,
                });
                if let Some(m) = metadata {
                    payload.as_object_mut().unwrap().insert("metadata".into(), Value::String(m));
                }
                if let Some(w) = webhook {
                    payload.as_object_mut().unwrap().insert("webhook_url".into(), Value::String(w));
                }
                ("POST", format!("{}/v2/images", base_url), Some(payload))
            }
            "get" => {
                let id = ctx.param_str("imageId")?;
                ("GET", format!("{}/v2/images/{}", base_url, id), None)
            }
            other => return Err(NodeError::Other(format!("bannerbear: unknown operation `{}`", other))),
        };

        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!("bannerbear: {}", e)))?;
        let status = resp.status();
        let parsed: Value = resp.json().await.unwrap_or(Value::Null);
        if !status.is_success() {
            return Err(NodeError::Http(format!("bannerbear {}: {}", status, parsed)));
        }
        Ok(vec![vec![NodeItem { json: parsed, ..Default::default() }]])
    }
}

inventory::submit! { NodeFactory::new("bannerbear", || Arc::new(BannerbearNode)) }
