// 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)
//
// `gitlab` — projects/issues via GitLab v4 REST API.
// Credential: gitlab = { base_url, 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::{json, Value};
use std::sync::Arc;

pub struct GitLabNode;

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

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let token = ctx.credential_field("access_token")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("gitlab.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://gitlab.com".to_string());
        let project_id = ctx.param_str("project_id")?;
        let operation = ctx.node_def.parameters.get("operation")
            .and_then(|v| v.as_str()).unwrap_or("list_issues").to_string();

        let (method, url, body): (&str, String, Option<Value>) = match operation.as_str() {
            "get_project" => ("GET", format!("{}/api/v4/projects/{}", base_url, urlencode(&project_id)), None),
            "list_issues" => ("GET", format!("{}/api/v4/projects/{}/issues", base_url, urlencode(&project_id)), None),
            "create_issue" => {
                let title = ctx.param_str("title")?;
                let description = ctx.param_opt_str("description").unwrap_or_default();
                ("POST", format!("{}/api/v4/projects/{}/issues", base_url, urlencode(&project_id)),
                 Some(json!({ "title": title, "description": description })))
            }
            other => return Err(NodeError::Other(format!("gitlab: unknown operation `{}`", other))),
        };

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