// 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)
//
// `strapi` — content entries via Strapi v3/v4 REST.
// Param names: resource (entry), operation, contentType, entryId,
// columns, additionalFields.
// Credential `strapiApi`: { email, password, url, apiVersion }.

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

static META: NodeMetadata = NodeMetadata {
    name: "strapi",
    display_name: "Strapi",
    version: &[1, 2],
    group: &["output"],
    description: "Read or create Strapi content entries",
    inputs: 1,
    outputs: 1,
    properties: &[
        PropertyDef { name: "resource", display_name: "Resource", kind: PropertyKind::Options, required: true, default: Some("entry") },
        PropertyDef { name: "operation", display_name: "Operation", kind: PropertyKind::Options, required: true, default: Some("getAll") },
        PropertyDef { name: "contentType", display_name: "Content Type", kind: PropertyKind::String, required: true, default: None },
        PropertyDef { name: "entryId", display_name: "Entry ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "columns", display_name: "Columns", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "data", display_name: "Data", kind: PropertyKind::Json, required: false, default: None },
    ],
    credentials: &[CredentialRef { name: "strapiApi", required: true }],
};

#[async_trait]
impl Node for StrapiNode {
    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("strapiApi.url".into()))?
            .trim_end_matches('/').to_string();
        // n8n's Strapi node first POSTs /admin/login or /api/auth/local to
        // exchange email+password for a JWT, then uses Authorization: Bearer.
        // For v0.1 we accept a pre-fetched JWT in `jwt` field; v0.2 will
        // wrap the login flow.
        let jwt = ctx.credential_field("jwt")
            .or_else(|_| ctx.credential_field("token"))
            .or_else(|_| ctx.credential_field("access_token"))?
            .as_str().ok_or_else(|| NodeError::MissingCredential(
                "strapiApi.jwt (pre-fetched JWT; auto-fetch via email/password lands in v0.2)".into()
            ))?
            .to_string();
        let api_version = ctx.credential_field("apiVersion").ok()
            .and_then(|v| v.as_str().map(|s| s.to_string()))
            .unwrap_or_else(|| "v4".to_string());
        let content_type = ctx.param_str("contentType")?;
        let operation = ctx.param_opt_str("operation").unwrap_or_else(|| "getAll".into());

        let endpoint = if api_version == "v3" {
            format!("{}/{}", url, content_type)
        } else {
            format!("{}/api/{}", url, content_type)
        };

        let (method, full_url, body): (&str, String, Option<Value>) = match operation.as_str() {
            "getAll" => ("GET", endpoint, None),
            "get" => {
                let id = ctx.param_str("entryId")?;
                ("GET", format!("{}/{}", endpoint, id), None)
            }
            "create" => {
                let data = ctx.node_def.parameters.get("data").cloned()
                    .unwrap_or(Value::Object(Default::default()));
                let payload = if api_version == "v3" { data.clone() } else { json!({ "data": data }) };
                ("POST", endpoint, Some(payload))
            }
            "update" => {
                let id = ctx.param_str("entryId")?;
                let data = ctx.node_def.parameters.get("data").cloned()
                    .unwrap_or(Value::Object(Default::default()));
                let payload = if api_version == "v3" { data.clone() } else { json!({ "data": data }) };
                ("PUT", format!("{}/{}", endpoint, id), Some(payload))
            }
            "delete" => {
                let id = ctx.param_str("entryId")?;
                ("DELETE", format!("{}/{}", endpoint, id), None)
            }
            other => return Err(NodeError::Other(format!("strapi: unknown operation `{}`", other))),
        };

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

inventory::submit! { NodeFactory::new("strapi", || Arc::new(StrapiNode)) }
