// 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)
//
// `dropbox` — list/upload/download via the Dropbox v2 API.
// Credential: dropbox = { 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 DropboxNode;

static META: NodeMetadata = NodeMetadata {
    name: "dropbox",
    display_name: "Dropbox",
    version: &[1, 2],
    group: &["output"],
    description: "List, upload, or download Dropbox files",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[CredentialRef { name: "dropbox", required: true }],
};

#[async_trait]
impl Node for DropboxNode {
    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("dropbox.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://api.dropboxapi.com".to_string());
        let operation = ctx.node_def.parameters.get("operation")
            .and_then(|v| v.as_str()).unwrap_or("list").to_string();

        let (url, body): (String, Value) = match operation.as_str() {
            "list" => {
                let path = ctx.param_opt_str("path").unwrap_or_default();
                (format!("{}/2/files/list_folder", base_url),
                 json!({ "path": path, "recursive": false }))
            }
            "get_metadata" => {
                let path = ctx.param_str("path")?;
                (format!("{}/2/files/get_metadata", base_url),
                 json!({ "path": path }))
            }
            other => return Err(NodeError::Other(format!("dropbox: unknown operation `{}`", other))),
        };

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

inventory::submit! { NodeFactory::new("dropbox", || Arc::new(DropboxNode)) }
