// 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)
//
// `mailerlite` — subscribers via the MailerLite API.
// Param names: resource (subscriber), operation, email, subscriberId.
// Credential `mailerLiteApi`: { apiKey, classicApi }.

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

static META: NodeMetadata = NodeMetadata {
    name: "mailerlite",
    display_name: "MailerLite",
    version: &[1, 2],
    group: &["output"],
    description: "Read or create MailerLite subscribers",
    inputs: 1,
    outputs: 1,
    properties: &[
        PropertyDef { name: "resource", display_name: "Resource", kind: PropertyKind::Options, required: true, default: Some("subscriber") },
        PropertyDef { name: "operation", display_name: "Operation", kind: PropertyKind::Options, required: true, default: Some("getAll") },
        PropertyDef { name: "email", display_name: "Email", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "subscriberId", display_name: "Subscriber ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "name", display_name: "Name", kind: PropertyKind::String, required: false, default: None },
    ],
    credentials: &[CredentialRef { name: "mailerLiteApi", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let api_key = ctx.credential_field("apiKey")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("mailerLiteApi.apiKey".into()))?
            .to_string();
        let classic = ctx.credential_field("classicApi").ok()
            .and_then(|v| v.as_bool()).unwrap_or(false);
        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(|| if classic {
                "https://api.mailerlite.com/api/v2".to_string()
            } else {
                "https://connect.mailerlite.com/api".to_string()
            });
        let operation = ctx.param_opt_str("operation").unwrap_or_else(|| "getAll".into());

        let (method, url, body): (&str, String, Option<Value>) = match operation.as_str() {
            "getAll" => ("GET", format!("{}/subscribers", base_url), None),
            "get" => {
                let id = ctx.param_str("subscriberId")?;
                ("GET", format!("{}/subscribers/{}", base_url, id), None)
            }
            "create" => {
                let email = ctx.param_str("email")?;
                let name = ctx.param_opt_str("name").unwrap_or_default();
                ("POST", format!("{}/subscribers", base_url),
                 Some(json!({ "email": email, "fields": { "name": name } })))
            }
            "update" => {
                let id = ctx.param_str("subscriberId")?;
                let name = ctx.param_opt_str("name");
                let mut payload = json!({});
                if let Some(n) = name {
                    payload.as_object_mut().unwrap().insert("fields".into(), json!({ "name": n }));
                }
                ("PUT", format!("{}/subscribers/{}", base_url, id), Some(payload))
            }
            "delete" => {
                let id = ctx.param_str("subscriberId")?;
                ("DELETE", format!("{}/subscribers/{}", base_url, id), None)
            }
            other => return Err(NodeError::Other(format!("mailerlite: unknown operation `{}`", other))),
        };

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

inventory::submit! { NodeFactory::new("mailerlite", || Arc::new(MailerLiteNode)) }
