// 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)
//
// `gotify` — push notifications via a self-hosted Gotify server.
// Param names: resource (message), operation, message, title, priority,
// messageId.
// Credential `gotifyApi`: { url, appToken }.

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

static META: NodeMetadata = NodeMetadata {
    name: "gotify",
    display_name: "Gotify",
    version: &[1],
    group: &["output"],
    description: "Send push notifications via a self-hosted Gotify server",
    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("create") },
        PropertyDef { name: "message", display_name: "Message", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "title", display_name: "Title", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "priority", display_name: "Priority", kind: PropertyKind::Number, required: false, default: Some("0") },
        PropertyDef { name: "messageId", display_name: "Message ID", kind: PropertyKind::String, required: false, default: None },
    ],
    credentials: &[CredentialRef { name: "gotifyApi", required: true }],
};

#[async_trait]
impl Node for GotifyNode {
    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("gotifyApi.url".into()))?
            .trim_end_matches('/').to_string();
        let app_token = ctx.credential_field("appToken")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("gotifyApi.appToken".into()))?
            .to_string();
        let operation = ctx.param_opt_str("operation").unwrap_or_else(|| "create".into());

        let (method, full_url, body): (&str, String, Option<Value>) = match operation.as_str() {
            "create" => {
                let message = ctx.param_str("message")?;
                let title = ctx.param_opt_str("title").unwrap_or_default();
                let priority = ctx.node_def.parameters.get("priority")
                    .and_then(|v| v.as_i64()).unwrap_or(0);
                ("POST", format!("{}/message?token={}", url, app_token),
                 Some(json!({
                     "message": message,
                     "title": title,
                     "priority": priority,
                 })))
            }
            "delete" => {
                let id = ctx.param_str("messageId")?;
                ("DELETE", format!("{}/message/{}", url, id), None)
            }
            "getAll" => ("GET", format!("{}/message", url), None),
            other => return Err(NodeError::Other(format!("gotify: unknown operation `{}`", other))),
        };

        let mut req = reqwest::Client::new().request(method.parse().unwrap(), &full_url);
        if matches!(operation.as_str(), "delete" | "getAll") {
            // Client API needs a different cred (clientToken), but Gotify
            // also accepts the appToken via the X-Gotify-Key header for
            // some endpoints.
            req = req.header("X-Gotify-Key", &app_token);
        }
        if let Some(b) = body { req = req.json(&b); }
        let resp = req.send().await.map_err(|e| NodeError::Http(format!("gotify: {}", e)))?;
        let status = resp.status();
        let parsed: Value = resp.json().await.unwrap_or(Value::Null);
        if !status.is_success() {
            return Err(NodeError::Http(format!("gotify {}: {}", status, parsed)));
        }
        Ok(vec![vec![NodeItem { json: parsed, ..Default::default() }]])
    }
}

inventory::submit! { NodeFactory::new("gotify", || Arc::new(GotifyNode)) }
