// 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_dynamics` — Microsoft Dynamics CRM accounts via Web API.
// Param names lifted verbatim from upstream MicrosoftDynamicsCrm.node.ts:
// resource (account), operation (create/delete/get/getAll/update),
// name, additionalFields, accountId, options, returnFields, expandFields,
// filters, query, returnAll, limit, updateFields.
// Credential `microsoftDynamicsOAuth2Api`: { subdomain, region, 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 MicrosoftDynamicsNode;

static META: NodeMetadata = NodeMetadata {
    name: "microsoft_dynamics",
    display_name: "Microsoft Dynamics CRM",
    version: &[1],
    group: &["input"],
    description: "Consume Microsoft Dynamics CRM API",
    inputs: 1,
    outputs: 1,
    properties: &[
        PropertyDef { name: "resource", display_name: "Resource", kind: PropertyKind::Options, required: true, default: Some("account") },
        PropertyDef { name: "operation", display_name: "Operation", kind: PropertyKind::Options, required: true, default: Some("getAll") },
        PropertyDef { name: "name", display_name: "Name", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "accountId", display_name: "Account ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "additionalFields", display_name: "Additional Fields", kind: PropertyKind::Json, required: false, default: None },
        PropertyDef { name: "updateFields", display_name: "Update Fields", kind: PropertyKind::Json, required: false, default: None },
        PropertyDef { name: "options", display_name: "Options", kind: PropertyKind::Json, required: false, default: None },
        PropertyDef { name: "filters", display_name: "Filters", kind: PropertyKind::Json, required: false, default: None },
        PropertyDef { name: "returnAll", display_name: "Return All", kind: PropertyKind::Boolean, required: false, default: Some("false") },
        PropertyDef { name: "limit", display_name: "Limit", kind: PropertyKind::Number, required: false, default: Some("50") },
    ],
    credentials: &[CredentialRef { name: "microsoftDynamicsOAuth2Api", required: true }],
};

#[async_trait]
impl Node for MicrosoftDynamicsNode {
    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("oauthTokenData.access_token"))
            .or_else(|_| ctx.credential_field("accessToken"))?
            .as_str().ok_or_else(|| NodeError::MissingCredential("microsoftDynamicsOAuth2Api.access_token".into()))?
            .to_string();
        let subdomain = ctx.credential_field("subdomain")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("microsoftDynamicsOAuth2Api.subdomain".into()))?
            .to_string();
        let region = ctx.credential_field("region").ok()
            .and_then(|v| v.as_str().map(|s| s.to_string()))
            .unwrap_or_else(|| "crm.dynamics.com".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(|| format!("https://{}.{}/api/data/v9.2", subdomain, region));

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

        if resource != "account" {
            return Err(NodeError::Other(format!("microsoft_dynamics: unknown resource `{}`", resource)));
        }

        let opts = ctx.node_def.parameters.get("options").cloned().unwrap_or(Value::Null);
        let return_fields = opts.get("returnFields").and_then(|v| v.as_array())
            .map(|a| a.iter().filter_map(|v| v.as_str()).collect::<Vec<_>>().join(","));
        let expand_fields = opts.get("expandFields").and_then(|v| v.as_array())
            .map(|a| a.iter().filter_map(|v| v.as_str()).collect::<Vec<_>>().join(","));

        let (method, url, body): (&str, String, Option<Value>) = match operation.as_str() {
            "create" => {
                let name = ctx.param_str("name")?;
                let additional = ctx.node_def.parameters.get("additionalFields").cloned()
                    .unwrap_or(Value::Object(Default::default()));
                let mut body = json!({ "name": name });
                if let Value::Object(map) = additional {
                    if let Value::Object(b) = &mut body {
                        for (k, v) in map { b.insert(k, v); }
                    }
                }
                let select = return_fields.clone().unwrap_or_else(|| "accountid".into());
                ("POST", format!("{}/accounts?$select={}", base_url, select), Some(body))
            }
            "delete" => {
                let id = ctx.param_str("accountId")?;
                ("DELETE", format!("{}/accounts({})", base_url, id), None)
            }
            "get" => {
                let id = ctx.param_str("accountId")?;
                let mut qs = vec![];
                if let Some(s) = return_fields { qs.push(format!("$select={}", s)); }
                if let Some(s) = expand_fields { qs.push(format!("$expand={}", s)); }
                let q = if qs.is_empty() { "".to_string() } else { format!("?{}", qs.join("&")) };
                ("GET", format!("{}/accounts({}){}", base_url, id, q), None)
            }
            "getAll" => {
                let return_all = ctx.node_def.parameters.get("returnAll")
                    .and_then(|v| v.as_bool()).unwrap_or(false);
                let limit = ctx.node_def.parameters.get("limit")
                    .and_then(|v| v.as_u64()).unwrap_or(50);
                let filters = ctx.node_def.parameters.get("filters").cloned().unwrap_or(Value::Null);
                let mut qs = vec![];
                if let Some(s) = return_fields { qs.push(format!("$select={}", s)); }
                if let Some(s) = expand_fields { qs.push(format!("$expand={}", s)); }
                if let Some(q) = filters.get("query").and_then(|v| v.as_str()) {
                    qs.push(format!("$filter={}", q));
                }
                if !return_all { qs.push(format!("$top={}", limit)); }
                let q = if qs.is_empty() { "".to_string() } else { format!("?{}", qs.join("&")) };
                ("GET", format!("{}/accounts{}", base_url, q), None)
            }
            "update" => {
                let id = ctx.param_str("accountId")?;
                let updates = ctx.node_def.parameters.get("updateFields").cloned()
                    .unwrap_or(Value::Object(Default::default()));
                let select = return_fields.clone().unwrap_or_else(|| "accountid".into());
                ("PATCH", format!("{}/accounts({})?$select={}", base_url, id, select), Some(updates))
            }
            other => return Err(NodeError::Other(format!("microsoft_dynamics: account.{} not implemented", other))),
        };

        let mut req = reqwest::Client::new()
            .request(method.parse().unwrap(), &url)
            .bearer_auth(&token)
            .header("OData-MaxVersion", "4.0")
            .header("OData-Version", "4.0")
            .header("Accept", "application/json")
            .header("Prefer", "return=representation");
        if let Some(b) = body { req = req.json(&b); }
        let resp = req.send().await.map_err(|e| NodeError::Http(format!("microsoft_dynamics: {}", 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_dynamics {}: {}", status, parsed)));
        }
        Ok(vec![vec![NodeItem { json: parsed, ..Default::default() }]])
    }
}

inventory::submit! { NodeFactory::new("microsoft_dynamics", || Arc::new(MicrosoftDynamicsNode)) }
