// 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)
//
// `mailgun` — send transactional email via the Mailgun v3 API.
// Param names: fromEmail, toEmail, ccEmail, bccEmail, subject, text, html.
// Credential `mailgunApi`: { apiDomain, emailDomain, apiKey }.

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

static META: NodeMetadata = NodeMetadata {
    name: "mailgun",
    display_name: "Mailgun",
    version: &[1],
    group: &["output"],
    description: "Send email via Mailgun",
    inputs: 1,
    outputs: 1,
    properties: &[
        PropertyDef { name: "fromEmail", display_name: "From Email", kind: PropertyKind::String, required: true, default: None },
        PropertyDef { name: "toEmail", display_name: "To Email", kind: PropertyKind::String, required: true, default: None },
        PropertyDef { name: "ccEmail", display_name: "CC Email", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "bccEmail", display_name: "BCC Email", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "subject", display_name: "Subject", kind: PropertyKind::String, required: true, default: None },
        PropertyDef { name: "text", display_name: "Text", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "html", display_name: "HTML", kind: PropertyKind::String, required: false, default: None },
    ],
    credentials: &[CredentialRef { name: "mailgunApi", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let api_domain = ctx.credential_field("apiDomain")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("mailgunApi.apiDomain".into()))?
            .trim_end_matches('/').to_string();
        let email_domain = ctx.credential_field("emailDomain")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("mailgunApi.emailDomain".into()))?
            .to_string();
        let api_key = ctx.credential_field("apiKey")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("mailgunApi.apiKey".into()))?
            .to_string();

        let from = ctx.param_str("fromEmail")?;
        let to = ctx.param_str("toEmail")?;
        let cc = ctx.param_opt_str("ccEmail");
        let bcc = ctx.param_opt_str("bccEmail");
        let subject = ctx.param_str("subject")?;
        let text = ctx.param_opt_str("text");
        let html = ctx.param_opt_str("html");

        let mut form: Vec<(&str, String)> = vec![
            ("from", from),
            ("to", to),
            ("subject", subject),
        ];
        if let Some(c) = cc { form.push(("cc", c)); }
        if let Some(b) = bcc { form.push(("bcc", b)); }
        if let Some(t) = text { form.push(("text", t)); }
        if let Some(h) = html { form.push(("html", h)); }

        let url = format!("{}/v3/{}/messages", api_domain, email_domain);
        let resp = reqwest::Client::new().post(&url)
            .basic_auth("api", Some(&api_key))
            .form(&form)
            .send().await.map_err(|e| NodeError::Http(format!("mailgun: {}", e)))?;
        let status = resp.status();
        let parsed: Value = resp.json().await.unwrap_or(Value::Null);
        if !status.is_success() {
            return Err(NodeError::Http(format!("mailgun {}: {}", status, parsed)));
        }
        Ok(vec![vec![NodeItem { json: parsed, ..Default::default() }]])
    }
}

inventory::submit! { NodeFactory::new("mailgun", || Arc::new(MailgunNode)) }
