// 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)
//
// `sendgrid` — send transactional email via SendGrid v3 API.
// Credential: sendgrid = { api_key = "SG.xxx" }

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

static META: NodeMetadata = NodeMetadata {
    name: "sendgrid",
    display_name: "SendGrid",
    version: &[1],
    group: &["output"],
    description: "Send email via SendGrid",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[CredentialRef { name: "sendgrid", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let api_key = ctx.credential_field("api_key")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("sendgrid.api_key".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.sendgrid.com".to_string());
        let from = ctx.param_str("from")?;
        let to = ctx.param_str("to")?;
        let subject = ctx.param_str("subject")?;
        let body = ctx.param_str("body")?;
        let is_html = ctx.node_def.parameters.get("html")
            .and_then(|v| v.as_bool()).unwrap_or(false);

        let payload = json!({
            "personalizations": [{ "to": [{ "email": to }] }],
            "from": { "email": from },
            "subject": subject,
            "content": [{
                "type": if is_html { "text/html" } else { "text/plain" },
                "value": body,
            }],
        });

        let resp = reqwest::Client::new()
            .post(format!("{}/v3/mail/send", base_url))
            .bearer_auth(&api_key)
            .json(&payload)
            .send().await.map_err(|e| NodeError::Http(format!("sendgrid: {}", e)))?;
        let status = resp.status();
        let body_text = resp.text().await.unwrap_or_default();
        if !status.is_success() {
            return Err(NodeError::Http(format!("sendgrid {}: {}", status, body_text)));
        }
        let parsed: Value = serde_json::from_str(&body_text).unwrap_or(json!({ "ok": true, "status": status.as_u16() }));
        Ok(vec![vec![NodeItem { json: parsed, ..Default::default() }]])
    }
}

inventory::submit! { NodeFactory::new("sendgrid", || Arc::new(SendgridNode)) }
