// 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)
//
// `cloudflare` — zone management via Cloudflare REST v4.
// Param names: resource (zoneCertificate), operation, zoneId, certificate,
// privateKey, certificateId.
// Credential `cloudflareApi`: { apiToken }.

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

static META: NodeMetadata = NodeMetadata {
    name: "cloudflare",
    display_name: "Cloudflare",
    version: &[1],
    group: &["output"],
    description: "Manage Cloudflare zones, DNS, and SSL certificates",
    inputs: 1,
    outputs: 1,
    properties: &[
        PropertyDef { name: "resource", display_name: "Resource", kind: PropertyKind::Options, required: true, default: Some("zoneCertificate") },
        PropertyDef { name: "operation", display_name: "Operation", kind: PropertyKind::Options, required: true, default: Some("get") },
        PropertyDef { name: "zoneId", display_name: "Zone ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "certificate", display_name: "Certificate (PEM)", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "privateKey", display_name: "Private Key (PEM)", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "certificateId", display_name: "Certificate ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "recordId", display_name: "DNS Record ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "recordType", display_name: "DNS Record Type", kind: PropertyKind::String, required: false, default: Some("A") },
        PropertyDef { name: "name", display_name: "DNS Name", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "content", display_name: "DNS Content", kind: PropertyKind::String, required: false, default: None },
    ],
    credentials: &[CredentialRef { name: "cloudflareApi", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let token = ctx.credential_field("apiToken").or_else(|_| ctx.credential_field("api_token"))?
            .as_str().ok_or_else(|| NodeError::MissingCredential("cloudflareApi.apiToken".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.cloudflare.com/client/v4".to_string());
        let resource = ctx.param_opt_str("resource").unwrap_or_else(|| "zoneCertificate".into());
        let operation = ctx.param_opt_str("operation").unwrap_or_else(|| "get".into());
        let zone_id = ctx.param_str("zoneId")?;

        let (method, url, body): (&str, String, Option<Value>) = match (resource.as_str(), operation.as_str()) {
            ("zoneCertificate", "get") => {
                let cert_id = ctx.param_str("certificateId")?;
                ("GET", format!("{}/zones/{}/custom_certificates/{}", base_url, zone_id, cert_id), None)
            }
            ("zoneCertificate", "getAll") => {
                ("GET", format!("{}/zones/{}/custom_certificates", base_url, zone_id), None)
            }
            ("zoneCertificate", "upload") => {
                let cert = ctx.param_str("certificate")?;
                let key = ctx.param_str("privateKey")?;
                ("POST", format!("{}/zones/{}/custom_certificates", base_url, zone_id),
                 Some(json!({ "certificate": cert, "private_key": key })))
            }
            ("zoneCertificate", "delete") => {
                let cert_id = ctx.param_str("certificateId")?;
                ("DELETE", format!("{}/zones/{}/custom_certificates/{}", base_url, zone_id, cert_id), None)
            }
            ("dnsRecord", "getAll") => {
                ("GET", format!("{}/zones/{}/dns_records", base_url, zone_id), None)
            }
            ("dnsRecord", "create") => {
                let r#type = ctx.param_opt_str("recordType").unwrap_or_else(|| "A".into());
                let name = ctx.param_str("name")?;
                let content = ctx.param_str("content")?;
                ("POST", format!("{}/zones/{}/dns_records", base_url, zone_id),
                 Some(json!({ "type": r#type, "name": name, "content": content })))
            }
            ("dnsRecord", "delete") => {
                let id = ctx.param_str("recordId")?;
                ("DELETE", format!("{}/zones/{}/dns_records/{}", base_url, zone_id, id), None)
            }
            (r, o) => return Err(NodeError::Other(format!("cloudflare: {}.{} 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!("cloudflare: {}", e)))?;
        let status = resp.status();
        let parsed: Value = resp.json().await.unwrap_or(Value::Null);
        if !status.is_success() {
            return Err(NodeError::Http(format!("cloudflare {}: {}", status, parsed)));
        }
        Ok(vec![vec![NodeItem { json: parsed, ..Default::default() }]])
    }
}

inventory::submit! { NodeFactory::new("cloudflare", || Arc::new(CloudflareNode)) }
