// 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)
//
// `google_drive` — list/get/create files and folders via Drive v3 API.
// Param names: resource, operation, fileId, folderId, name, mimeType.
// Credential `googleDriveOAuth2Api`: { 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 GoogleDriveNode;

static META: NodeMetadata = NodeMetadata {
    name: "google_drive",
    display_name: "Google Drive",
    version: &[1, 2],
    group: &["output"],
    description: "List, get, and create Google Drive files and folders",
    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("getAll") },
        PropertyDef { name: "fileId", display_name: "File ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "folderId", 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 },
        PropertyDef { name: "mimeType", display_name: "MIME Type", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "query", display_name: "Search Query (q)", kind: PropertyKind::String, required: false, default: None },
    ],
    credentials: &[CredentialRef { name: "googleDriveOAuth2Api", required: true }],
};

#[async_trait]
impl Node for GoogleDriveNode {
    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("googleDriveOAuth2Api.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://www.googleapis.com".to_string());
        let resource = ctx.param_opt_str("resource").unwrap_or_else(|| "file".into());
        let operation = ctx.param_opt_str("operation").unwrap_or_else(|| "getAll".into());

        let (method, url, body): (&str, String, Option<Value>) = match (resource.as_str(), operation.as_str()) {
            ("file", "getAll") => {
                let q = ctx.param_opt_str("query").map(|s| format!("?q={}", urlencode(&s))).unwrap_or_default();
                ("GET", format!("{}/drive/v3/files{}", base_url, q), None)
            }
            ("file", "get") => {
                let id = ctx.param_str("fileId")?;
                ("GET", format!("{}/drive/v3/files/{}", base_url, id), None)
            }
            ("file", "delete") => {
                let id = ctx.param_str("fileId")?;
                ("DELETE", format!("{}/drive/v3/files/{}", base_url, id), None)
            }
            ("folder", "create") => {
                let name = ctx.param_str("name")?;
                let parent = ctx.param_opt_str("folderId");
                let mut payload = json!({
                    "name": name,
                    "mimeType": "application/vnd.google-apps.folder",
                });
                if let Some(p) = parent {
                    payload.as_object_mut().unwrap().insert("parents".into(), json!([p]));
                }
                ("POST", format!("{}/drive/v3/files", base_url), Some(payload))
            }
            (r, o) => return Err(NodeError::Other(format!("google_drive: {}.{} 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!("google_drive: {}", e)))?;
        let status = resp.status();
        let parsed: Value = resp.json().await.unwrap_or(Value::Null);
        if !status.is_success() {
            return Err(NodeError::Http(format!("google_drive {}: {}", status, parsed)));
        }
        Ok(vec![vec![NodeItem { json: parsed, ..Default::default() }]])
    }
}

fn urlencode(s: &str) -> String {
    s.bytes().flat_map(|b| {
        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') { vec![b as char] }
        else { format!("%{:02X}", b).chars().collect() }
    }).collect()
}

inventory::submit! { NodeFactory::new("google_drive", || Arc::new(GoogleDriveNode)) }
