// 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)
//
// `convertkit` — subscriber/tag management via the ConvertKit API.
// Param names: resource (subscriber/tag/tagSubscriber/customField), operation,
// tagId, email, subscriberId, customFieldId.
// Credential `convertKitApi`: { apiSecret }.

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

static META: NodeMetadata = NodeMetadata {
    name: "convertkit",
    display_name: "ConvertKit",
    version: &[1],
    group: &["output"],
    description: "Manage ConvertKit subscribers, tags, and custom fields",
    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: "tagId", display_name: "Tag ID", kind: PropertyKind::String, required: false, default: None },
        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: "customFieldId", display_name: "Custom Field ID", kind: PropertyKind::String, required: false, default: None },
    ],
    credentials: &[CredentialRef { name: "convertKitApi", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let api_secret = ctx.credential_field("apiSecret")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("convertKitApi.apiSecret".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.convertkit.com".to_string());
        let resource = ctx.param_opt_str("resource").unwrap_or_else(|| "subscriber".into());
        let operation = ctx.param_opt_str("operation").unwrap_or_else(|| "getAll".into());

        let (method, url, body): (&str, String, Option<Value>) = match (resource.as_str(), operation.as_str()) {
            ("subscriber", "getAll") => {
                ("GET", format!("{}/v3/subscribers?api_secret={}", base_url, urlencode(&api_secret)), None)
            }
            ("subscriber", "get") => {
                let id = ctx.param_str("subscriberId")?;
                ("GET", format!("{}/v3/subscribers/{}?api_secret={}", base_url, id, urlencode(&api_secret)), None)
            }
            ("tag", "getAll") => {
                ("GET", format!("{}/v3/tags?api_secret={}", base_url, urlencode(&api_secret)), None)
            }
            ("tagSubscriber", "add") => {
                let tag_id = ctx.param_str("tagId")?;
                let email = ctx.param_str("email")?;
                ("POST", format!("{}/v3/tags/{}/subscribe", base_url, tag_id),
                 Some(json!({ "api_secret": api_secret, "email": email })))
            }
            ("tagSubscriber", "delete") => {
                let tag_id = ctx.param_str("tagId")?;
                let email = ctx.param_str("email")?;
                ("POST", format!("{}/v3/tags/{}/unsubscribe", base_url, tag_id),
                 Some(json!({ "api_secret": api_secret, "email": email })))
            }
            ("customField", "getAll") => {
                ("GET", format!("{}/v3/custom_fields?api_secret={}", base_url, urlencode(&api_secret)), None)
            }
            (r, o) => return Err(NodeError::Other(format!("convertkit: {}.{} not implemented", r, o))),
        };

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

fn urlencode(s: &str) -> String {
    s.bytes().flat_map(|b| {
        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') { vec![b as char] }
        else { format!("%{:02X}", b).chars().collect() }
    }).collect()
}

inventory::submit! { NodeFactory::new("convertkit", || Arc::new(ConvertKitNode)) }
