// 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)
//
// `twist` — channels / threads / messages via Twist REST.
// Param names: resource (channel/thread/comment), operation, threadId,
// content, channelId, workspaceId.
// Credential `twistOAuth2Api`: { access_token }.

use async_trait::async_trait;
use crate::core::error::NodeError;
use crate::core::types::*;
use crate::engine::{ExecuteCtx, Node, NodeFactory};
use serde_json::Value;
use std::sync::Arc;

pub struct TwistNode;

static META: NodeMetadata = NodeMetadata {
    name: "twist",
    display_name: "Twist",
    version: &[1],
    group: &["output"],
    description: "Read or post Twist channels, threads, and comments",
    inputs: 1,
    outputs: 1,
    properties: &[
        PropertyDef { name: "resource", display_name: "Resource", kind: PropertyKind::Options, required: true, default: Some("comment") },
        PropertyDef { name: "operation", display_name: "Operation", kind: PropertyKind::Options, required: true, default: Some("create") },
        PropertyDef { name: "threadId", display_name: "Thread ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "content", display_name: "Content", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "channelId", display_name: "Channel ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "workspaceId", display_name: "Workspace ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "title", display_name: "Title", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "commentId", display_name: "Comment ID", kind: PropertyKind::String, required: false, default: None },
    ],
    credentials: &[CredentialRef { name: "twistOAuth2Api", required: true }],
};

#[async_trait]
impl Node for TwistNode {
    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("twistOAuth2Api.access_token".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.twist.com".to_string());
        let resource = ctx.param_opt_str("resource").unwrap_or_else(|| "comment".into());
        let operation = ctx.param_opt_str("operation").unwrap_or_else(|| "create".into());

        // Twist uses ?token= in the URL or Authorization: Bearer; we use Bearer.
        let url = match (resource.as_str(), operation.as_str()) {
            ("comment", "create") => {
                let thread = ctx.param_str("threadId")?;
                let content = ctx.param_str("content")?;
                format!("{}/api/v3/comments/add?thread_id={}&content={}",
                    base_url, thread, urlencode(&content))
            }
            ("comment", "get") => {
                let id = ctx.param_str("commentId")?;
                format!("{}/api/v3/comments/getone?id={}", base_url, id)
            }
            ("comment", "delete") => {
                let id = ctx.param_str("commentId")?;
                format!("{}/api/v3/comments/remove?id={}", base_url, id)
            }
            ("thread", "create") => {
                let channel = ctx.param_str("channelId")?;
                let title = ctx.param_str("title")?;
                let content = ctx.param_str("content")?;
                format!("{}/api/v3/threads/add?channel_id={}&title={}&content={}",
                    base_url, channel, urlencode(&title), urlencode(&content))
            }
            ("channel", "getAll") => {
                let workspace = ctx.param_str("workspaceId")?;
                format!("{}/api/v3/channels/get?workspace_id={}", base_url, workspace)
            }
            (r, o) => return Err(NodeError::Other(format!("twist: {}.{} not implemented", r, o))),
        };

        let method = if matches!((resource.as_str(), operation.as_str()),
            ("comment", "create") | ("thread", "create") | ("comment", "delete")) { "POST" } else { "GET" };

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

fn urlencode(s: &str) -> String {
    s.bytes().flat_map(|b| {
        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') { vec![b as char] }
        else { format!("%{:02X}", b).chars().collect() }
    }).collect()
}

inventory::submit! { NodeFactory::new("twist", || Arc::new(TwistNode)) }
