// 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)
//
// `gmail` — list/get/send via the Gmail v1 API.
// Credential: gmail = { access_token = "...", base_url? = "..." }
// (OAuth refresh flow is v0.2 — for now bring a fresh access_token.)

use async_trait::async_trait;
use crate::core::error::NodeError;
use crate::core::types::*;
use crate::engine::{ExecuteCtx, Node, NodeFactory};
use base64::Engine as _;
use serde_json::{json, Value};
use std::sync::Arc;

pub struct GmailNode;

static META: NodeMetadata = NodeMetadata {
    name: "gmail",
    display_name: "Gmail",
    version: &[1, 2],
    group: &["output"],
    description: "Send, list, or fetch Gmail messages",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[CredentialRef { name: "gmail", required: true }],
};

#[async_trait]
impl Node for GmailNode {
    fn metadata(&self) -> &'static NodeMetadata { &META }

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let token = ctx.credential_field("access_token")?
            .as_str()
            .ok_or_else(|| NodeError::MissingCredential("gmail.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://gmail.googleapis.com".to_string());
        let user_id = ctx.node_def.parameters.get("user_id")
            .and_then(|v| v.as_str()).unwrap_or("me").to_string();
        let operation = ctx.node_def.parameters.get("operation")
            .and_then(|v| v.as_str()).unwrap_or("list_messages").to_string();

        let (method, url, body): (&str, String, Option<Value>) = match operation.as_str() {
            "list_messages" => ("GET", format!("{}/gmail/v1/users/{}/messages", base_url, user_id), None),
            "get_message" => {
                let id = ctx.param_str("message_id")?;
                ("GET", format!("{}/gmail/v1/users/{}/messages/{}", base_url, user_id, id), None)
            }
            "send" => {
                let from = ctx.param_str("from")?;
                let to = ctx.param_str("to")?;
                let subject = ctx.param_str("subject")?;
                let body_text = ctx.param_str("body")?;
                let raw = format!("From: {}\r\nTo: {}\r\nSubject: {}\r\n\r\n{}", from, to, subject, body_text);
                let encoded = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(raw.as_bytes());
                ("POST", format!("{}/gmail/v1/users/{}/messages/send", base_url, user_id),
                 Some(json!({ "raw": encoded })))
            }
            other => return Err(NodeError::Other(format!("gmail: 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!("gmail: {}", e)))?;
        let status = resp.status();
        let parsed: Value = resp.json().await.unwrap_or(Value::Null);
        if !status.is_success() {
            return Err(NodeError::Http(format!("gmail {}: {}", status, parsed)));
        }
        Ok(vec![vec![NodeItem { json: parsed, ..Default::default() }]])
    }
}

inventory::submit! { NodeFactory::new("gmail", || Arc::new(GmailNode)) }
