// 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)
//
// `webflow` — CMS items via the Webflow REST API.
// Param names: resource (item), operation, siteId, collectionId, itemId.
// Credential `webflowApi`: { accessToken }.

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

static META: NodeMetadata = NodeMetadata {
    name: "webflow",
    display_name: "Webflow",
    version: &[1, 2],
    group: &["output"],
    description: "Read or create Webflow CMS items",
    inputs: 1,
    outputs: 1,
    properties: &[
        PropertyDef { name: "resource", display_name: "Resource", kind: PropertyKind::Options, required: true, default: Some("item") },
        PropertyDef { name: "operation", display_name: "Operation", kind: PropertyKind::Options, required: true, default: Some("getAll") },
        PropertyDef { name: "siteId", display_name: "Site ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "collectionId", display_name: "Collection ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "itemId", display_name: "Item ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "fields", display_name: "Fields", kind: PropertyKind::Json, required: false, default: None },
    ],
    credentials: &[CredentialRef { name: "webflowApi", required: true }],
};

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

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

        let (method, url, body): (&str, String, Option<Value>) = match operation.as_str() {
            "getAll" => {
                let collection = ctx.param_str("collectionId")?;
                ("GET", format!("{}/v2/collections/{}/items", base_url, collection), None)
            }
            "get" => {
                let collection = ctx.param_str("collectionId")?;
                let item = ctx.param_str("itemId")?;
                ("GET", format!("{}/v2/collections/{}/items/{}", base_url, collection, item), None)
            }
            "create" => {
                let collection = ctx.param_str("collectionId")?;
                let fields = ctx.node_def.parameters.get("fields").cloned()
                    .unwrap_or(Value::Object(Default::default()));
                ("POST", format!("{}/v2/collections/{}/items", base_url, collection),
                 Some(json!({ "fieldData": fields })))
            }
            "delete" => {
                let collection = ctx.param_str("collectionId")?;
                let item = ctx.param_str("itemId")?;
                ("DELETE", format!("{}/v2/collections/{}/items/{}", base_url, collection, item), None)
            }
            other => return Err(NodeError::Other(format!("webflow: unknown operation `{}`", other))),
        };

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

inventory::submit! { NodeFactory::new("webflow", || Arc::new(WebflowNode)) }
