// 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)
//
// `zendesk` — tickets via the Zendesk REST API.
// Credential: zendesk = { subdomain, email, api_token }

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

static META: NodeMetadata = NodeMetadata {
    name: "zendesk",
    display_name: "Zendesk",
    version: &[1, 2],
    group: &["output"],
    description: "Read or create Zendesk tickets",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[CredentialRef { name: "zendesk", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let token = ctx.credential_field("api_token")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("zendesk.api_token".into()))?
            .to_string();
        let email = ctx.credential_field("email")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("zendesk.email".into()))?
            .to_string();
        let base_url = match ctx.credential_field("base_url").ok().and_then(|v| v.as_str().map(|s| s.trim_end_matches('/').to_string())) {
            Some(u) => u,
            None => {
                let sub = ctx.credential_field("subdomain")?
                    .as_str().ok_or_else(|| NodeError::MissingCredential("zendesk.subdomain".into()))?
                    .to_string();
                format!("https://{}.zendesk.com", sub)
            }
        };
        let operation = ctx.node_def.parameters.get("operation")
            .and_then(|v| v.as_str()).unwrap_or("get_ticket").to_string();

        let (method, url, body): (&str, String, Option<Value>) = match operation.as_str() {
            "get_ticket" => {
                let id = ctx.param_str("ticket_id")?;
                ("GET", format!("{}/api/v2/tickets/{}.json", base_url, id), None)
            }
            "create_ticket" => {
                let subject = ctx.param_str("subject")?;
                let body_text = ctx.param_str("body")?;
                ("POST", format!("{}/api/v2/tickets.json", base_url),
                 Some(json!({ "ticket": { "subject": subject, "comment": { "body": body_text } } })))
            }
            other => return Err(NodeError::Other(format!("zendesk: unknown operation `{}`", other))),
        };

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

inventory::submit! { NodeFactory::new("zendesk", || Arc::new(ZendeskNode)) }
