// 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)
//
// `bubble` — Data API for a Bubble.io app.
// Param names: resource (object), operation, typeName, objectId, properties.
// Credential `bubbleApi`: { apiToken, appName, environment, hosting? }.

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

static META: NodeMetadata = NodeMetadata {
    name: "bubble",
    display_name: "Bubble",
    version: &[1],
    group: &["output"],
    description: "Read or write objects in a Bubble.io app via Data API",
    inputs: 1,
    outputs: 1,
    properties: &[
        PropertyDef { name: "resource", display_name: "Resource", kind: PropertyKind::Options, required: true, default: Some("object") },
        PropertyDef { name: "operation", display_name: "Operation", kind: PropertyKind::Options, required: true, default: Some("get") },
        PropertyDef { name: "typeName", display_name: "Type Name", kind: PropertyKind::String, required: true, default: None },
        PropertyDef { name: "objectId", display_name: "Object ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "properties", display_name: "Properties", kind: PropertyKind::Json, required: false, default: None },
    ],
    credentials: &[CredentialRef { name: "bubbleApi", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let token = ctx.credential_field("apiToken")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("bubbleApi.apiToken".into()))?
            .to_string();
        let app_name = ctx.credential_field("appName")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("bubbleApi.appName".into()))?
            .to_string();
        let environment = ctx.credential_field("environment").ok()
            .and_then(|v| v.as_str().map(|s| s.to_string()))
            .unwrap_or_else(|| "Development".to_string());
        // Bubble URLs:
        //   prod:  https://<app>.bubbleapps.io/api/1.1/obj/<type>
        //   dev:   https://<app>.bubbleapps.io/version-test/api/1.1/obj/<type>
        let env_seg = if environment == "Development" { "/version-test" } else { "" };
        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(|| format!("https://{}.bubbleapps.io{}", app_name, env_seg));

        let type_name = ctx.param_str("typeName")?;
        let operation = ctx.param_opt_str("operation").unwrap_or_else(|| "get".into());

        let (method, url, body): (&str, String, Option<Value>) = match operation.as_str() {
            "create" => {
                let props = ctx.node_def.parameters.get("properties").cloned()
                    .unwrap_or(Value::Object(Default::default()));
                ("POST", format!("{}/api/1.1/obj/{}", base_url, type_name), Some(props))
            }
            "get" => {
                let id = ctx.param_str("objectId")?;
                ("GET", format!("{}/api/1.1/obj/{}/{}", base_url, type_name, id), None)
            }
            "update" => {
                let id = ctx.param_str("objectId")?;
                let props = ctx.node_def.parameters.get("properties").cloned()
                    .unwrap_or(Value::Object(Default::default()));
                ("PATCH", format!("{}/api/1.1/obj/{}/{}", base_url, type_name, id), Some(props))
            }
            "delete" => {
                let id = ctx.param_str("objectId")?;
                ("DELETE", format!("{}/api/1.1/obj/{}/{}", base_url, type_name, id), None)
            }
            "getAll" => ("GET", format!("{}/api/1.1/obj/{}", base_url, type_name), None),
            other => return Err(NodeError::Other(format!("bubble: unknown operation `{}`", other))),
        };

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

inventory::submit! { NodeFactory::new("bubble", || Arc::new(BubbleNode)) }
