// 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)
//
// `notion` — read/append blocks against the Notion REST API.
// Credential: notion = { token = "secret_...", base_url? = "..." }
// Operations: get_page (default), append_block_children, query_database.

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 NotionNode;

static META: NodeMetadata = NodeMetadata {
    name: "notion",
    display_name: "Notion",
    version: &[1, 2],
    group: &["output"],
    description: "Read pages, append blocks, and query databases via the Notion API",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[CredentialRef { name: "notion", required: true }],
};

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

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

        let client = reqwest::Client::new();
        let (method, url, body): (&str, String, Option<Value>) = match operation.as_str() {
            "get_page" => {
                let id = ctx.param_str("page_id")?;
                ("GET", format!("{}/v1/pages/{}", base_url, id), None)
            }
            "append_block_children" => {
                let id = ctx.param_str("block_id")?;
                let children = ctx.node_def.parameters.get("children").cloned()
                    .ok_or_else(|| NodeError::MissingParameter("children".into()))?;
                ("PATCH", format!("{}/v1/blocks/{}/children", base_url, id),
                 Some(json!({ "children": children })))
            }
            "query_database" => {
                let id = ctx.param_str("database_id")?;
                let filter = ctx.node_def.parameters.get("filter").cloned();
                let body = match filter {
                    Some(f) => json!({ "filter": f }),
                    None => json!({}),
                };
                ("POST", format!("{}/v1/databases/{}/query", base_url, id), Some(body))
            }
            other => return Err(NodeError::Other(format!("notion: unknown operation `{}`", other))),
        };

        let mut req = client.request(method.parse().unwrap(), &url)
            .bearer_auth(&token)
            .header("Notion-Version", "2022-06-28");
        if let Some(b) = body { req = req.json(&b); }
        let resp = req.send().await.map_err(|e| NodeError::Http(format!("notion: {}", e)))?;
        let status = resp.status();
        let parsed: Value = resp.json().await.unwrap_or(Value::Null);
        if !status.is_success() {
            return Err(NodeError::Http(format!("notion {}: {}", status, parsed)));
        }
        Ok(vec![vec![NodeItem { json: parsed, ..Default::default() }]])
    }
}

inventory::submit! { NodeFactory::new("notion", || Arc::new(NotionNode)) }
