// 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)
//
// `twilio` — send SMS/MMS via the Twilio REST API.
// Credential: twilio = { account_sid, auth_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 TwilioNode;

static META: NodeMetadata = NodeMetadata {
    name: "twilio",
    display_name: "Twilio",
    version: &[1],
    group: &["output"],
    description: "Send SMS/MMS via the Twilio API",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[CredentialRef { name: "twilio", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let sid = ctx.credential_field("account_sid")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("twilio.account_sid".into()))?
            .to_string();
        let token = ctx.credential_field("auth_token")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("twilio.auth_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.twilio.com".to_string());
        let from = ctx.param_str("from")?;
        let to = ctx.param_str("to")?;
        let body = ctx.param_str("body")?;

        let url = format!("{}/2010-04-01/Accounts/{}/Messages.json", base_url, sid);
        let form = vec![
            ("From", from.as_str()),
            ("To", to.as_str()),
            ("Body", body.as_str()),
        ];
        let resp = reqwest::Client::new()
            .post(&url)
            .basic_auth(&sid, Some(&token))
            .form(&form)
            .send().await.map_err(|e| NodeError::Http(format!("twilio: {}", e)))?;
        let status = resp.status();
        let parsed: Value = resp.json().await.unwrap_or(Value::Null);
        if !status.is_success() {
            return Err(NodeError::Http(format!("twilio {}: {}", status, parsed)));
        }
        Ok(vec![vec![NodeItem { json: parsed, ..Default::default() }]])
    }
}

inventory::submit! { NodeFactory::new("twilio", || Arc::new(TwilioNode)) }
