// 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)
//
// `wordpress` — posts/users via the WordPress REST API.
// Param names match n8n: resource, operation, title, content, status, postId.
// Credential `wordpressApi`: { url, username, password }.

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

static META: NodeMetadata = NodeMetadata {
    name: "wordpress",
    display_name: "WordPress",
    version: &[1],
    group: &["output"],
    description: "Read or create WordPress posts",
    inputs: 1,
    outputs: 1,
    properties: &[
        PropertyDef { name: "resource", display_name: "Resource", kind: PropertyKind::Options, required: true, default: Some("post") },
        PropertyDef { name: "operation", display_name: "Operation", kind: PropertyKind::Options, required: true, default: Some("create") },
        PropertyDef { name: "title", display_name: "Title", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "content", display_name: "Content", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "status", display_name: "Status", kind: PropertyKind::Options, required: false, default: Some("publish") },
        PropertyDef { name: "postId", display_name: "Post ID", kind: PropertyKind::String, required: false, default: None },
    ],
    credentials: &[CredentialRef { name: "wordpressApi", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let url = ctx.credential_field("url")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("wordpressApi.url".into()))?
            .trim_end_matches('/').to_string();
        let username = ctx.credential_field("username")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("wordpressApi.username".into()))?
            .to_string();
        let password = ctx.credential_field("password")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("wordpressApi.password".into()))?
            .to_string();
        let resource = ctx.param_opt_str("resource").unwrap_or_else(|| "post".into());
        let operation = ctx.param_opt_str("operation").unwrap_or_else(|| "create".into());

        let endpoint = format!("{}/wp-json/wp/v2/{}s", url, resource);
        let (method, full_url, body): (&str, String, Option<Value>) = match operation.as_str() {
            "create" => {
                let title = ctx.param_opt_str("title").unwrap_or_default();
                let content = ctx.param_opt_str("content").unwrap_or_default();
                let status = ctx.param_opt_str("status").unwrap_or_else(|| "publish".into());
                ("POST", endpoint,
                 Some(json!({ "title": title, "content": content, "status": status })))
            }
            "get" => {
                let post_id = ctx.param_str("postId")?;
                ("GET", format!("{}/{}", endpoint, post_id), None)
            }
            "getAll" => ("GET", endpoint, None),
            "update" => {
                let post_id = ctx.param_str("postId")?;
                let title = ctx.param_opt_str("title");
                let content = ctx.param_opt_str("content");
                let status = ctx.param_opt_str("status");
                let mut b = json!({});
                if let Some(t) = title { b.as_object_mut().unwrap().insert("title".into(), Value::String(t)); }
                if let Some(c) = content { b.as_object_mut().unwrap().insert("content".into(), Value::String(c)); }
                if let Some(s) = status { b.as_object_mut().unwrap().insert("status".into(), Value::String(s)); }
                ("POST", format!("{}/{}", endpoint, post_id), Some(b))
            }
            other => return Err(NodeError::Other(format!("wordpress: unknown operation `{}`", other))),
        };

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

inventory::submit! { NodeFactory::new("wordpress", || Arc::new(WordpressNode)) }
