// 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)
//
// `jira` — issue CRUD via Jira Cloud REST API v3.
// Credential: jira = { base_url, 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 JiraNode;

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

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let base_url = ctx.credential_field("base_url")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("jira.base_url".into()))?
            .trim_end_matches('/').to_string();
        let email = ctx.credential_field("email").ok().and_then(|v| v.as_str().map(|s| s.to_string()));
        let token = ctx.credential_field("api_token")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("jira.api_token".into()))?
            .to_string();
        let operation = ctx.node_def.parameters.get("operation")
            .and_then(|v| v.as_str()).unwrap_or("get_issue").to_string();

        let (method, url, body): (&str, String, Option<Value>) = match operation.as_str() {
            "get_issue" => {
                let key = ctx.param_str("issue_key")?;
                ("GET", format!("{}/rest/api/3/issue/{}", base_url, key), None)
            }
            "create_issue" => {
                let project = ctx.param_str("project_key")?;
                let summary = ctx.param_str("summary")?;
                let issue_type = ctx.param_opt_str("issue_type").unwrap_or_else(|| "Task".into());
                ("POST", format!("{}/rest/api/3/issue", base_url),
                 Some(json!({
                    "fields": {
                        "project": { "key": project },
                        "summary": summary,
                        "issuetype": { "name": issue_type }
                    }
                 })))
            }
            "search" => {
                let jql = ctx.param_str("jql")?;
                ("GET", format!("{}/rest/api/3/search?jql={}", base_url, urlencode(&jql)), None)
            }
            other => return Err(NodeError::Other(format!("jira: unknown operation `{}`", other))),
        };

        let mut req = reqwest::Client::new().request(method.parse().unwrap(), &url);
        match email {
            Some(e) => { req = req.basic_auth(e, Some(&token)); }
            None => { req = req.bearer_auth(&token); }
        }
        if let Some(b) = body { req = req.json(&b); }
        let resp = req.send().await.map_err(|e| NodeError::Http(format!("jira: {}", e)))?;
        let status = resp.status();
        let parsed: Value = resp.json().await.unwrap_or(Value::Null);
        if !status.is_success() {
            return Err(NodeError::Http(format!("jira {}: {}", 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("jira", || Arc::new(JiraNode)) }
