// 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)
//
// `microsoft_onedrive` — files / folders via Microsoft Graph.
// Param names: resource (file/folder), operation, itemId, parentId, name.
// Credential `microsoftOneDriveOAuth2Api`: { 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 MicrosoftOneDriveNode;

static META: NodeMetadata = NodeMetadata {
    name: "microsoft_onedrive",
    display_name: "Microsoft OneDrive",
    version: &[1],
    group: &["output"],
    description: "Read and manage OneDrive files and folders via Microsoft Graph",
    inputs: 1,
    outputs: 1,
    properties: &[
        PropertyDef { name: "resource", display_name: "Resource", kind: PropertyKind::Options, required: true, default: Some("file") },
        PropertyDef { name: "operation", display_name: "Operation", kind: PropertyKind::Options, required: true, default: Some("get") },
        PropertyDef { name: "itemId", display_name: "Item ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "parentId", display_name: "Parent Folder ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "name", display_name: "Name", kind: PropertyKind::String, required: false, default: None },
    ],
    credentials: &[CredentialRef { name: "microsoftOneDriveOAuth2Api", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let token = ctx.credential_field("access_token")
            .or_else(|_| ctx.credential_field("accessToken"))?
            .as_str().ok_or_else(|| NodeError::MissingCredential("microsoftOneDriveOAuth2Api.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://graph.microsoft.com/v1.0".to_string());
        let resource = ctx.param_opt_str("resource").unwrap_or_else(|| "file".into());
        let operation = ctx.param_opt_str("operation").unwrap_or_else(|| "get".into());

        let (method, url, body): (&str, String, Option<Value>) = match (resource.as_str(), operation.as_str()) {
            ("file", "get") => {
                let id = ctx.param_str("itemId")?;
                ("GET", format!("{}/me/drive/items/{}", base_url, id), None)
            }
            ("file", "delete") => {
                let id = ctx.param_str("itemId")?;
                ("DELETE", format!("{}/me/drive/items/{}", base_url, id), None)
            }
            ("folder", "create") => {
                let name = ctx.param_str("name")?;
                let parent = ctx.param_opt_str("parentId");
                let parent_segment = match parent.as_deref() {
                    Some(p) if !p.is_empty() => format!("items/{}", p),
                    _ => "root".to_string(),
                };
                ("POST", format!("{}/me/drive/{}/children", base_url, parent_segment),
                 Some(json!({
                     "name": name,
                     "folder": {},
                     "@microsoft.graph.conflictBehavior": "rename",
                 })))
            }
            ("folder", "list") => {
                let parent = ctx.param_opt_str("parentId");
                let url = match parent {
                    Some(p) if !p.is_empty() => format!("{}/me/drive/items/{}/children", base_url, p),
                    _ => format!("{}/me/drive/root/children", base_url),
                };
                ("GET", url, None)
            }
            (r, o) => return Err(NodeError::Other(format!("microsoft_onedrive: {}.{} not implemented", r, o))),
        };

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

inventory::submit! { NodeFactory::new("microsoft_onedrive", || Arc::new(MicrosoftOneDriveNode)) }
