// 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)
//
// `mautic` — contact + company management via Mautic REST.
// Param names: resource (contact/company/segment), operation, contactId,
// companyId, name, email.
// Credential `mauticOAuth2Api` or `mauticCredentialsApi` (basic).

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

static META: NodeMetadata = NodeMetadata {
    name: "mautic",
    display_name: "Mautic",
    version: &[1],
    group: &["output"],
    description: "Read or create Mautic contacts, companies, and segments",
    inputs: 1,
    outputs: 1,
    properties: &[
        PropertyDef { name: "resource", display_name: "Resource", kind: PropertyKind::Options, required: true, default: Some("contact") },
        PropertyDef { name: "operation", display_name: "Operation", kind: PropertyKind::Options, required: true, default: Some("create") },
        PropertyDef { name: "contactId", display_name: "Contact ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "companyId", display_name: "Company ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "name", display_name: "Name", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "email", display_name: "Email", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "firstName", display_name: "First Name", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "lastName", display_name: "Last Name", kind: PropertyKind::String, required: false, default: None },
    ],
    credentials: &[CredentialRef { name: "mauticOAuth2Api", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let token = ctx.credential_field("access_token")
            .or_else(|_| ctx.credential_field("accessToken"))?
            .as_str().ok_or_else(|| NodeError::MissingCredential("mauticOAuth2Api.access_token".into()))?
            .to_string();
        let base_url = ctx.credential_field("url")
            .or_else(|_| ctx.credential_field("base_url"))?
            .as_str().ok_or_else(|| NodeError::MissingCredential("mauticOAuth2Api.url".into()))?
            .trim_end_matches('/').to_string();
        let resource = ctx.param_opt_str("resource").unwrap_or_else(|| "contact".into());
        let operation = ctx.param_opt_str("operation").unwrap_or_else(|| "create".into());

        let (method, url, body): (&str, String, Option<Value>) = match (resource.as_str(), operation.as_str()) {
            ("contact", "create") => {
                let email = ctx.param_str("email")?;
                let first = ctx.param_opt_str("firstName").unwrap_or_default();
                let last = ctx.param_opt_str("lastName").unwrap_or_default();
                ("POST", format!("{}/api/contacts/new", base_url),
                 Some(json!({ "email": email, "firstname": first, "lastname": last })))
            }
            ("contact", "get") => {
                let id = ctx.param_str("contactId")?;
                ("GET", format!("{}/api/contacts/{}", base_url, id), None)
            }
            ("contact", "getAll") => ("GET", format!("{}/api/contacts", base_url), None),
            ("contact", "delete") => {
                let id = ctx.param_str("contactId")?;
                ("DELETE", format!("{}/api/contacts/{}/delete", base_url, id), None)
            }
            ("company", "create") => {
                let name = ctx.param_str("name")?;
                ("POST", format!("{}/api/companies/new", base_url),
                 Some(json!({ "companyname": name })))
            }
            ("company", "get") => {
                let id = ctx.param_str("companyId")?;
                ("GET", format!("{}/api/companies/{}", base_url, id), None)
            }
            (r, o) => return Err(NodeError::Other(format!("mautic: {}.{} not implemented", r, o))),
        };

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

inventory::submit! { NodeFactory::new("mautic", || Arc::new(MauticNode)) }
