// 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)
//
// `github` — small subset of the REST API: get repo, list issues,
// create issue, create comment.
// Credential: github = { token = "ghp_..." }

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

static META: NodeMetadata = NodeMetadata {
    name: "github",
    display_name: "GitHub",
    version: &[1, 2],
    group: &["output"],
    description: "Interact with the GitHub REST API",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[CredentialRef { name: "github", required: true }],
};

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

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

        let client = reqwest::Client::builder()
            .user_agent(concat!("r8r/", env!("CARGO_PKG_VERSION")))
            .build()
            .map_err(|e| NodeError::Http(e.to_string()))?;

        let (method, url, body): (&str, String, Option<Value>) = match operation.as_str() {
            "get_repo" => ("GET", format!("{}/repos/{}/{}", base_url, owner, repo), None),
            "list_issues" => ("GET", format!("{}/repos/{}/{}/issues", base_url, owner, repo), None),
            "create_issue" => {
                let title = ctx.param_str("title")?;
                let body_text = ctx.param_opt_str("body").unwrap_or_default();
                ("POST", format!("{}/repos/{}/{}/issues", base_url, owner, repo),
                 Some(json!({ "title": title, "body": body_text })))
            }
            "create_comment" => {
                let issue_number = ctx.node_def.parameters.get("issue_number")
                    .and_then(|v| v.as_u64())
                    .ok_or_else(|| NodeError::MissingParameter("issue_number".into()))?;
                let body_text = ctx.param_str("body")?;
                ("POST", format!("{}/repos/{}/{}/issues/{}/comments", base_url, owner, repo, issue_number),
                 Some(json!({ "body": body_text })))
            }
            other => return Err(NodeError::Other(format!("github: unknown operation `{}`", other))),
        };

        let mut req = client.request(method.parse().unwrap(), &url)
            .bearer_auth(&token)
            .header("Accept", "application/vnd.github+json")
            .header("X-GitHub-Api-Version", "2022-11-28");
        if let Some(b) = body { req = req.json(&b); }

        let resp = req.send().await.map_err(|e| NodeError::Http(format!("github: {}", e)))?;
        let status = resp.status();
        let parsed: Value = resp.json().await.unwrap_or(Value::Null);
        if !status.is_success() {
            return Err(NodeError::Http(format!("github {}: {}", status, parsed)));
        }
        let items = match &parsed {
            Value::Array(arr) => arr.iter().map(|j| NodeItem { json: j.clone(), ..Default::default() }).collect(),
            _ => vec![NodeItem { json: parsed, ..Default::default() }],
        };
        Ok(vec![items])
    }
}

inventory::submit! { NodeFactory::new("github", || Arc::new(GitHubNode)) }
