// 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)
//
// `airtable` — list/create/update records via the Airtable REST API.
// Credential: airtable = { api_key = "patXXX...", base_url? = "..." }

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

static META: NodeMetadata = NodeMetadata {
    name: "airtable",
    display_name: "Airtable",
    version: &[1, 2],
    group: &["output"],
    description: "List, create, or update Airtable records",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[CredentialRef { name: "airtable", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let api_key = ctx.credential_field("api_key")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("airtable.api_key".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.airtable.com".to_string());
        let base = ctx.param_str("base_id")?;
        let table = ctx.param_str("table")?;
        let operation = ctx.node_def.parameters.get("operation")
            .and_then(|v| v.as_str()).unwrap_or("list").to_string();

        let (method, url, body): (&str, String, Option<Value>) = match operation.as_str() {
            "list" => ("GET", format!("{}/v0/{}/{}", base_url, base, table), None),
            "get" => {
                let id = ctx.param_str("record_id")?;
                ("GET", format!("{}/v0/{}/{}/{}", base_url, base, table, id), None)
            }
            "create" => {
                let fields = ctx.node_def.parameters.get("fields").cloned()
                    .unwrap_or(Value::Object(Default::default()));
                ("POST", format!("{}/v0/{}/{}", base_url, base, table),
                 Some(json!({ "records": [{ "fields": fields }] })))
            }
            other => return Err(NodeError::Other(format!("airtable: unknown operation `{}`", other))),
        };

        let mut req = reqwest::Client::new().request(method.parse().unwrap(), &url).bearer_auth(&api_key);
        if let Some(b) = body { req = req.json(&b); }
        let resp = req.send().await.map_err(|e| NodeError::Http(format!("airtable: {}", e)))?;
        let status = resp.status();
        let parsed: Value = resp.json().await.unwrap_or(Value::Null);
        if !status.is_success() {
            return Err(NodeError::Http(format!("airtable {}: {}", status, parsed)));
        }
        Ok(vec![vec![NodeItem { json: parsed, ..Default::default() }]])
    }
}

inventory::submit! { NodeFactory::new("airtable", || Arc::new(AirtableNode)) }
