// 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)
//
// `mailchimp` — list members + add subscribers via Mailchimp Marketing API v3.
// Credential: mailchimp = { api_key = "xxx-us12", server_prefix? = "us12" }

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

static META: NodeMetadata = NodeMetadata {
    name: "mailchimp",
    display_name: "Mailchimp",
    version: &[1, 2],
    group: &["output"],
    description: "Manage Mailchimp audiences and members",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[CredentialRef { name: "mailchimp", required: true }],
};

#[async_trait]
impl Node for MailchimpNode {
    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("mailchimp.api_key".into()))?
            .to_string();
        let base_url = match ctx.credential_field("base_url").ok().and_then(|v| v.as_str().map(|s| s.trim_end_matches('/').to_string())) {
            Some(u) => u,
            None => {
                let prefix = ctx.credential_field("server_prefix").ok()
                    .and_then(|v| v.as_str().map(|s| s.to_string()))
                    .or_else(|| api_key.rsplit_once('-').map(|(_, p)| p.to_string()))
                    .ok_or_else(|| NodeError::MissingCredential("mailchimp.server_prefix or api_key with -prefix suffix".into()))?;
                format!("https://{}.api.mailchimp.com", prefix)
            }
        };
        let list_id = ctx.param_str("list_id")?;
        let operation = ctx.node_def.parameters.get("operation")
            .and_then(|v| v.as_str()).unwrap_or("list_members").to_string();

        let (method, url, body): (&str, String, Option<Value>) = match operation.as_str() {
            "list_members" => ("GET", format!("{}/3.0/lists/{}/members", base_url, list_id), None),
            "add_member" => {
                let email = ctx.param_str("email")?;
                ("POST", format!("{}/3.0/lists/{}/members", base_url, list_id),
                 Some(json!({ "email_address": email, "status": "subscribed" })))
            }
            other => return Err(NodeError::Other(format!("mailchimp: unknown operation `{}`", other))),
        };

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

inventory::submit! { NodeFactory::new("mailchimp", || Arc::new(MailchimpNode)) }
