// 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_excel` — workbook + worksheet operations via Microsoft Graph.
// Param names: resource (workbook/worksheet/table), operation, workbookId,
// worksheetId, range, values.
// Credential `microsoftExcelOAuth2Api`: { 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 MicrosoftExcelNode;

static META: NodeMetadata = NodeMetadata {
    name: "microsoft_excel",
    display_name: "Microsoft Excel",
    version: &[1, 2],
    group: &["output"],
    description: "Read and write Excel workbooks via Microsoft Graph",
    inputs: 1,
    outputs: 1,
    properties: &[
        PropertyDef { name: "resource", display_name: "Resource", kind: PropertyKind::Options, required: true, default: Some("workbook") },
        PropertyDef { name: "operation", display_name: "Operation", kind: PropertyKind::Options, required: true, default: Some("getAll") },
        PropertyDef { name: "workbookId", display_name: "Workbook ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "worksheetId", display_name: "Worksheet ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "range", display_name: "Range", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "values", display_name: "Values", kind: PropertyKind::Json, required: false, default: None },
    ],
    credentials: &[CredentialRef { name: "microsoftExcelOAuth2Api", required: true }],
};

#[async_trait]
impl Node for MicrosoftExcelNode {
    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("microsoftExcelOAuth2Api.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(|| "workbook".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()) {
            ("workbook", "getAll") => {
                ("GET", format!("{}/me/drive/root/search(q='.xlsx')", base_url), None)
            }
            ("workbook", "get") => {
                let wb = ctx.param_str("workbookId")?;
                ("GET", format!("{}/me/drive/items/{}", base_url, wb), None)
            }
            ("worksheet", "getAll") => {
                let wb = ctx.param_str("workbookId")?;
                ("GET", format!("{}/me/drive/items/{}/workbook/worksheets", base_url, wb), None)
            }
            ("worksheet", "getRange") => {
                let wb = ctx.param_str("workbookId")?;
                let ws = ctx.param_str("worksheetId")?;
                let range = ctx.param_str("range")?;
                ("GET", format!("{}/me/drive/items/{}/workbook/worksheets/{}/range(address='{}')",
                    base_url, wb, ws, range), None)
            }
            ("worksheet", "appendRange") => {
                let wb = ctx.param_str("workbookId")?;
                let ws = ctx.param_str("worksheetId")?;
                let range = ctx.param_str("range")?;
                let values = ctx.node_def.parameters.get("values").cloned()
                    .unwrap_or(Value::Array(vec![]));
                ("PATCH", format!("{}/me/drive/items/{}/workbook/worksheets/{}/range(address='{}')",
                    base_url, wb, ws, range),
                 Some(json!({ "values": values })))
            }
            (r, o) => return Err(NodeError::Other(format!("microsoft_excel: {}.{} 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_excel: {}", 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_excel {}: {}", status, parsed)));
        }
        Ok(vec![vec![NodeItem { json: parsed, ..Default::default() }]])
    }
}

inventory::submit! { NodeFactory::new("microsoft_excel", || Arc::new(MicrosoftExcelNode)) }
