// 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)
//
// `bitwarden` — collection / member / group via Bitwarden Public API.
// Param names: resource (collection/member/group), operation,
// collectionId, memberId, groupId.
// Credential `bitwardenApi`: { clientId, clientSecret, environment, domain }.
// Federal-relevant: secrets management, self-hostable.

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

static META: NodeMetadata = NodeMetadata {
    name: "bitwarden",
    display_name: "Bitwarden",
    version: &[1],
    group: &["output"],
    description: "Manage Bitwarden organization collections, members, and groups",
    inputs: 1,
    outputs: 1,
    properties: &[
        PropertyDef { name: "resource", display_name: "Resource", kind: PropertyKind::Options, required: true, default: Some("collection") },
        PropertyDef { name: "operation", display_name: "Operation", kind: PropertyKind::Options, required: true, default: Some("getAll") },
        PropertyDef { name: "collectionId", display_name: "Collection ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "memberId", display_name: "Member ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "groupId", display_name: "Group ID", kind: PropertyKind::String, required: false, default: None },
    ],
    credentials: &[CredentialRef { name: "bitwardenApi", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let access_token = ctx.credential_field("access_token")
            .or_else(|_| ctx.credential_field("accessToken"))?
            .as_str().ok_or_else(|| NodeError::MissingCredential(
                "bitwardenApi.access_token (resolve client_credentials before execute, v0.2 will auto-fetch)".into()
            ))?.to_string();
        let environment = ctx.credential_field("environment").ok()
            .and_then(|v| v.as_str().map(|s| s.to_string()))
            .unwrap_or_else(|| "Cloud-Hosted".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(|| match environment.as_str() {
                "Self-Hosted" => {
                    let domain = ctx.credential_field("domain").ok()
                        .and_then(|v| v.as_str().map(|s| s.trim_end_matches('/').to_string()))
                        .unwrap_or_default();
                    format!("{}/api/public", domain)
                }
                _ => "https://api.bitwarden.com/public".to_string(),
            });

        let resource = ctx.param_opt_str("resource").unwrap_or_else(|| "collection".into());
        let operation = ctx.param_opt_str("operation").unwrap_or_else(|| "getAll".into());

        let url = match (resource.as_str(), operation.as_str()) {
            ("collection", "getAll") => format!("{}/collections", base_url),
            ("collection", "get") => {
                let id = ctx.param_str("collectionId")?;
                format!("{}/collections/{}", base_url, id)
            }
            ("collection", "delete") => {
                let id = ctx.param_str("collectionId")?;
                format!("{}/collections/{}", base_url, id)
            }
            ("member", "getAll") => format!("{}/members", base_url),
            ("member", "get") => {
                let id = ctx.param_str("memberId")?;
                format!("{}/members/{}", base_url, id)
            }
            ("group", "getAll") => format!("{}/groups", base_url),
            ("group", "get") => {
                let id = ctx.param_str("groupId")?;
                format!("{}/groups/{}", base_url, id)
            }
            (r, o) => return Err(NodeError::Other(format!("bitwarden: {}.{} not implemented", r, o))),
        };

        let method = if operation == "delete" { "DELETE" } else { "GET" };
        let resp = reqwest::Client::new().request(method.parse().unwrap(), &url).bearer_auth(&access_token)
            .send().await.map_err(|e| NodeError::Http(format!("bitwarden: {}", e)))?;
        let status = resp.status();
        let parsed: Value = resp.json().await.unwrap_or(Value::Null);
        if !status.is_success() {
            return Err(NodeError::Http(format!("bitwarden {}: {}", status, parsed)));
        }
        Ok(vec![vec![NodeItem { json: parsed, ..Default::default() }]])
    }
}

inventory::submit! { NodeFactory::new("bitwarden", || Arc::new(BitwardenNode)) }
