// 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)
//
// `mattermost` — post messages, manage channels via Mattermost REST.
// Param names: resource, operation, channelId, message.
// Credential `mattermostApi`: { accessToken, baseUrl, allowUnauthorizedCerts }.

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

static META: NodeMetadata = NodeMetadata {
    name: "mattermost",
    display_name: "Mattermost",
    version: &[1, 2],
    group: &["output"],
    description: "Post messages and manage channels in Mattermost",
    inputs: 1,
    outputs: 1,
    properties: &[
        PropertyDef { name: "resource", display_name: "Resource", kind: PropertyKind::Options, required: true, default: Some("message") },
        PropertyDef { name: "operation", display_name: "Operation", kind: PropertyKind::Options, required: true, default: Some("post") },
        PropertyDef { name: "channelId", display_name: "Channel ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "message", display_name: "Message", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "userId", display_name: "User ID (postEphemeral)", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "postId", display_name: "Post ID", kind: PropertyKind::String, required: false, default: None },
    ],
    credentials: &[CredentialRef { name: "mattermostApi", required: true }],
};

#[async_trait]
impl Node for MattermostNode {
    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("mattermostApi.accessToken".into()))?
            .to_string();
        let base_url = ctx.credential_field("baseUrl")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("mattermostApi.baseUrl".into()))?
            .trim_end_matches('/').to_string();
        let allow_unauth = ctx.credential_field("allowUnauthorizedCerts").ok()
            .and_then(|v| v.as_bool()).unwrap_or(false);
        let resource = ctx.param_opt_str("resource").unwrap_or_else(|| "message".into());
        let operation = ctx.param_opt_str("operation").unwrap_or_else(|| "post".into());

        let client = reqwest::Client::builder()
            .danger_accept_invalid_certs(allow_unauth)
            .build().map_err(|e| NodeError::Http(format!("mattermost: client: {}", e)))?;

        let (method, url, body): (&str, String, Option<Value>) = match (resource.as_str(), operation.as_str()) {
            ("message", "post") => {
                let channel_id = ctx.param_str("channelId")?;
                let message = ctx.param_str("message")?;
                ("POST", format!("{}/api/v4/posts", base_url),
                 Some(json!({ "channel_id": channel_id, "message": message })))
            }
            ("message", "postEphemeral") => {
                let channel_id = ctx.param_str("channelId")?;
                let user_id = ctx.param_str("userId")?;
                let message = ctx.param_str("message")?;
                ("POST", format!("{}/api/v4/posts/ephemeral", base_url),
                 Some(json!({
                     "user_id": user_id,
                     "post": { "channel_id": channel_id, "message": message }
                 })))
            }
            ("message", "delete") => {
                let post_id = ctx.param_str("postId")?;
                ("DELETE", format!("{}/api/v4/posts/{}", base_url, post_id), None)
            }
            ("channel", "get") => {
                let channel_id = ctx.param_str("channelId")?;
                ("GET", format!("{}/api/v4/channels/{}", base_url, channel_id), None)
            }
            (r, o) => return Err(NodeError::Other(format!("mattermost: {}.{} not implemented", r, o))),
        };

        let mut req = client.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!("mattermost: {}", e)))?;
        let status = resp.status();
        let parsed: Value = resp.json().await.unwrap_or(Value::Null);
        if !status.is_success() {
            return Err(NodeError::Http(format!("mattermost {}: {}", status, parsed)));
        }
        Ok(vec![vec![NodeItem { json: parsed, ..Default::default() }]])
    }
}

inventory::submit! { NodeFactory::new("mattermost", || Arc::new(MattermostNode)) }
