// 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_outlook` — send / list / get messages via Microsoft Graph.
// Param names lifted from n8n source: resource, operation, toRecipients,
// subject, bodyContent, messageId.
// Credential `microsoftOutlookOAuth2Api`: { 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 MicrosoftOutlookNode;

static META: NodeMetadata = NodeMetadata {
    name: "microsoft_outlook",
    display_name: "Microsoft Outlook",
    version: &[1, 2],
    group: &["output"],
    description: "Send, read, and manage Outlook messages via Microsoft Graph",
    inputs: 1,
    outputs: 1,
    properties: &[
        PropertyDef { name: "resource", display_name: "Resource", kind: PropertyKind::Options, required: true, default: Some("message") },
        PropertyDef { name: "operation", display_name: "Operation", kind: PropertyKind::Options, required: true, default: Some("send") },
        PropertyDef { name: "toRecipients", display_name: "To", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "subject", display_name: "Subject", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "bodyContent", display_name: "Body Content", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "messageId", display_name: "Message ID", kind: PropertyKind::String, required: false, default: None },
    ],
    credentials: &[CredentialRef { name: "microsoftOutlookOAuth2Api", required: true }],
};

#[async_trait]
impl Node for MicrosoftOutlookNode {
    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("microsoftOutlookOAuth2Api.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 operation = ctx.param_opt_str("operation").unwrap_or_else(|| "send".into());

        let (method, url, body): (&str, String, Option<Value>) = match operation.as_str() {
            "send" => {
                let to = ctx.param_str("toRecipients")?;
                let subject = ctx.param_str("subject")?;
                let body_content = ctx.param_str("bodyContent")?;
                let recipients: Vec<Value> = to.split(',').map(|addr| {
                    json!({ "emailAddress": { "address": addr.trim() } })
                }).collect();
                ("POST", format!("{}/me/sendMail", base_url),
                 Some(json!({
                     "message": {
                         "subject": subject,
                         "body": { "contentType": "Text", "content": body_content },
                         "toRecipients": recipients,
                     },
                     "saveToSentItems": true,
                 })))
            }
            "get" => {
                let id = ctx.param_str("messageId")?;
                ("GET", format!("{}/me/messages/{}", base_url, id), None)
            }
            "getAll" => ("GET", format!("{}/me/messages", base_url), None),
            "delete" => {
                let id = ctx.param_str("messageId")?;
                ("DELETE", format!("{}/me/messages/{}", base_url, id), None)
            }
            other => return Err(NodeError::Other(format!("microsoft_outlook: unknown operation `{}`", other))),
        };

        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_outlook: {}", e)))?;
        let status = resp.status();
        // sendMail returns 202 No Content with no body
        if status == reqwest::StatusCode::ACCEPTED || status == reqwest::StatusCode::NO_CONTENT {
            return Ok(vec![vec![NodeItem {
                json: json!({ "ok": true, "status": status.as_u16() }),
                ..Default::default()
            }]]);
        }
        let parsed: Value = resp.json().await.unwrap_or(Value::Null);
        if !status.is_success() {
            return Err(NodeError::Http(format!("microsoft_outlook {}: {}", status, parsed)));
        }
        Ok(vec![vec![NodeItem { json: parsed, ..Default::default() }]])
    }
}

inventory::submit! { NodeFactory::new("microsoft_outlook", || Arc::new(MicrosoftOutlookNode)) }
