// 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)
//
// `intercom` — contacts/conversations via Intercom v2.10 API.
// Credential: intercom = { 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::{json, Value};
use std::sync::Arc;

pub struct IntercomNode;

static META: NodeMetadata = NodeMetadata {
    name: "intercom",
    display_name: "Intercom",
    version: &[1, 2],
    group: &["output"],
    description: "Read or create Intercom contacts",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[CredentialRef { name: "intercom", required: true }],
};

#[async_trait]
impl Node for IntercomNode {
    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("intercom.access_token".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.intercom.io".to_string());
        let operation = ctx.node_def.parameters.get("operation")
            .and_then(|v| v.as_str()).unwrap_or("list_contacts").to_string();

        let (method, url, body): (&str, String, Option<Value>) = match operation.as_str() {
            "list_contacts" => ("GET", format!("{}/contacts", base_url), None),
            "get_contact" => {
                let id = ctx.param_str("contact_id")?;
                ("GET", format!("{}/contacts/{}", base_url, id), None)
            }
            "create_contact" => {
                let email = ctx.param_str("email")?;
                let role = ctx.param_opt_str("role").unwrap_or_else(|| "user".into());
                ("POST", format!("{}/contacts", base_url),
                 Some(json!({ "email": email, "role": role })))
            }
            other => return Err(NodeError::Other(format!("intercom: unknown operation `{}`", other))),
        };

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

inventory::submit! { NodeFactory::new("intercom", || Arc::new(IntercomNode)) }
