// 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)
//
// `salesforce` — SObject CRUD + SOQL via Salesforce REST.
// Credential: salesforce = { instance_url, access_token }
// (OAuth2 refresh flow is v0.2 — bring a fresh access_token.)

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

static META: NodeMetadata = NodeMetadata {
    name: "salesforce",
    display_name: "Salesforce",
    version: &[1, 2],
    group: &["output"],
    description: "Salesforce SObject CRUD + SOQL queries",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[CredentialRef { name: "salesforce", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let token = ctx.credential_field("access_token")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("salesforce.access_token".into()))?
            .to_string();
        let instance_url = ctx.credential_field("instance_url")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("salesforce.instance_url".into()))?
            .trim_end_matches('/').to_string();
        let api_version = ctx.param_opt_str("api_version").unwrap_or_else(|| "v60.0".into());
        let operation = ctx.node_def.parameters.get("operation")
            .and_then(|v| v.as_str()).unwrap_or("query").to_string();

        let (method, url, body): (&str, String, Option<Value>) = match operation.as_str() {
            "query" => {
                let soql = ctx.param_str("query")?;
                ("GET", format!("{}/services/data/{}/query?q={}", instance_url, api_version, urlencode(&soql)), None)
            }
            "get" => {
                let object = ctx.param_str("sobject")?;
                let id = ctx.param_str("id")?;
                ("GET", format!("{}/services/data/{}/sobjects/{}/{}", instance_url, api_version, object, id), None)
            }
            "create" => {
                let object = ctx.param_str("sobject")?;
                let fields = ctx.node_def.parameters.get("fields").cloned()
                    .unwrap_or(Value::Object(Default::default()));
                ("POST", format!("{}/services/data/{}/sobjects/{}", instance_url, api_version, object), Some(fields))
            }
            other => return Err(NodeError::Other(format!("salesforce: 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!("salesforce: {}", e)))?;
        let status = resp.status();
        let parsed: Value = resp.json().await.unwrap_or(Value::Null);
        if !status.is_success() {
            return Err(NodeError::Http(format!("salesforce {}: {}", status, parsed)));
        }
        Ok(vec![vec![NodeItem { json: parsed, ..Default::default() }]])
    }
}

fn urlencode(s: &str) -> String {
    s.bytes().flat_map(|b| {
        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') { vec![b as char] }
        else { format!("%{:02X}", b).chars().collect() }
    }).collect()
}

inventory::submit! { NodeFactory::new("salesforce", || Arc::new(SalesforceNode)) }
