// 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_teams` — post messages to a Teams channel or chat via
// the Microsoft Graph API. Param names lifted from n8n source:
// resource, operation, teamId, channelId, chatId, message, contentType.
// Credential `microsoftTeamsOAuth2Api` (OAuth2 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 MicrosoftTeamsNode;

static META: NodeMetadata = NodeMetadata {
    name: "microsoft_teams",
    display_name: "Microsoft Teams",
    version: &[1, 2],
    group: &["output"],
    description: "Post messages to Microsoft Teams channels and chats",
    inputs: 1,
    outputs: 1,
    properties: &[
        PropertyDef { name: "resource", display_name: "Resource", kind: PropertyKind::Options, required: true, default: Some("channelMessage") },
        PropertyDef { name: "operation", display_name: "Operation", kind: PropertyKind::Options, required: true, default: Some("create") },
        PropertyDef { name: "teamId", display_name: "Team ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "channelId", display_name: "Channel ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "chatId", display_name: "Chat ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "message", display_name: "Message", kind: PropertyKind::String, required: true, default: None },
        PropertyDef { name: "contentType", display_name: "Content Type", kind: PropertyKind::Options, required: false, default: Some("text") },
    ],
    credentials: &[CredentialRef { name: "microsoftTeamsOAuth2Api", required: true }],
};

#[async_trait]
impl Node for MicrosoftTeamsNode {
    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("microsoftTeamsOAuth2Api.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(|| "channelMessage".into());
        let message = ctx.param_str("message")?;
        let content_type = ctx.param_opt_str("contentType").unwrap_or_else(|| "text".into());

        let url = match resource.as_str() {
            "channelMessage" => {
                let team_id = ctx.param_str("teamId")?;
                let channel_id = ctx.param_str("channelId")?;
                format!("{}/teams/{}/channels/{}/messages", base_url, team_id, channel_id)
            }
            "chatMessage" => {
                let chat_id = ctx.param_str("chatId")?;
                format!("{}/chats/{}/messages", base_url, chat_id)
            }
            other => return Err(NodeError::Other(format!("microsoft_teams: unknown resource `{}`", other))),
        };

        let body = json!({
            "body": { "contentType": content_type, "content": message }
        });

        let resp = reqwest::Client::new().post(&url).bearer_auth(&token)
            .json(&body)
            .send().await.map_err(|e| NodeError::Http(format!("microsoft_teams: {}", 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_teams {}: {}", status, parsed)));
        }
        Ok(vec![vec![NodeItem { json: parsed, ..Default::default() }]])
    }
}

inventory::submit! { NodeFactory::new("microsoft_teams", || Arc::new(MicrosoftTeamsNode)) }
