// 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)
//
// `bitbucket` — repos/issues via Bitbucket v2.0 REST API.
// Credential: bitbucket = { username, app_password }
// (Atlassian moves to OAuth-only in 2026 — app passwords still work today)

use async_trait::async_trait;
use crate::core::error::NodeError;
use crate::core::types::*;
use crate::engine::{ExecuteCtx, Node, NodeFactory};
use serde_json::Value;
use std::sync::Arc;

pub struct BitbucketNode;

static META: NodeMetadata = NodeMetadata {
    name: "bitbucket",
    display_name: "Bitbucket",
    version: &[1],
    group: &["output"],
    description: "Read Bitbucket repos and issues",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[CredentialRef { name: "bitbucket", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let username = ctx.credential_field("username")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("bitbucket.username".into()))?
            .to_string();
        let app_password = ctx.credential_field("app_password")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("bitbucket.app_password".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.bitbucket.org".to_string());
        let workspace = ctx.param_str("workspace")?;
        let repo = ctx.param_str("repo_slug")?;
        let operation = ctx.node_def.parameters.get("operation")
            .and_then(|v| v.as_str()).unwrap_or("get_repo").to_string();

        let url = match operation.as_str() {
            "get_repo" => format!("{}/2.0/repositories/{}/{}", base_url, workspace, repo),
            "list_issues" => format!("{}/2.0/repositories/{}/{}/issues", base_url, workspace, repo),
            "list_commits" => format!("{}/2.0/repositories/{}/{}/commits", base_url, workspace, repo),
            other => return Err(NodeError::Other(format!("bitbucket: unknown operation `{}`", other))),
        };

        let resp = reqwest::Client::new().get(&url)
            .basic_auth(&username, Some(&app_password))
            .send().await.map_err(|e| NodeError::Http(format!("bitbucket: {}", e)))?;
        let status = resp.status();
        let parsed: Value = resp.json().await.unwrap_or(Value::Null);
        if !status.is_success() {
            return Err(NodeError::Http(format!("bitbucket {}: {}", status, parsed)));
        }
        Ok(vec![vec![NodeItem { json: parsed, ..Default::default() }]])
    }
}

inventory::submit! { NodeFactory::new("bitbucket", || Arc::new(BitbucketNode)) }
