// 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)
//
// `coda` — table rows + formulas via Coda v1 REST.
// Param names: resource (table/formula/control), operation, docId,
// tableId, rowId, columns, options, formulaId, controlId.
// Credential `codaApi`: { accessToken }.

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

static META: NodeMetadata = NodeMetadata {
    name: "coda",
    display_name: "Coda",
    version: &[1],
    group: &["output"],
    description: "Read or write rows in Coda tables",
    inputs: 1,
    outputs: 1,
    properties: &[
        PropertyDef { name: "resource", display_name: "Resource", kind: PropertyKind::Options, required: true, default: Some("table") },
        PropertyDef { name: "operation", display_name: "Operation", kind: PropertyKind::Options, required: true, default: Some("getAllRows") },
        PropertyDef { name: "docId", display_name: "Doc ID", kind: PropertyKind::String, required: true, default: None },
        PropertyDef { name: "tableId", display_name: "Table ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "rowId", display_name: "Row ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "columns", display_name: "Columns", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "rows", display_name: "Rows", kind: PropertyKind::Json, required: false, default: None },
        PropertyDef { name: "formulaId", display_name: "Formula ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "controlId", display_name: "Control ID", kind: PropertyKind::String, required: false, default: None },
    ],
    credentials: &[CredentialRef { name: "codaApi", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let token = ctx.credential_field("accessToken")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("codaApi.accessToken".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://coda.io".to_string());
        let doc_id = ctx.param_str("docId")?;
        let resource = ctx.param_opt_str("resource").unwrap_or_else(|| "table".into());
        let operation = ctx.param_opt_str("operation").unwrap_or_else(|| "getAllRows".into());

        let (method, url, body): (&str, String, Option<Value>) = match (resource.as_str(), operation.as_str()) {
            ("table", "getAllRows") => {
                let table = ctx.param_str("tableId")?;
                ("GET", format!("{}/apis/v1/docs/{}/tables/{}/rows", base_url, doc_id, table), None)
            }
            ("table", "getRow") => {
                let table = ctx.param_str("tableId")?;
                let row = ctx.param_str("rowId")?;
                ("GET", format!("{}/apis/v1/docs/{}/tables/{}/rows/{}", base_url, doc_id, table, row), None)
            }
            ("table", "createRow") => {
                let table = ctx.param_str("tableId")?;
                let rows = ctx.node_def.parameters.get("rows").cloned()
                    .unwrap_or(Value::Array(vec![]));
                ("POST", format!("{}/apis/v1/docs/{}/tables/{}/rows", base_url, doc_id, table),
                 Some(json!({ "rows": rows })))
            }
            ("table", "deleteRow") => {
                let table = ctx.param_str("tableId")?;
                let row = ctx.param_str("rowId")?;
                ("DELETE", format!("{}/apis/v1/docs/{}/tables/{}/rows/{}", base_url, doc_id, table, row), None)
            }
            ("formula", "get") => {
                let id = ctx.param_str("formulaId")?;
                ("GET", format!("{}/apis/v1/docs/{}/formulas/{}", base_url, doc_id, id), None)
            }
            ("control", "get") => {
                let id = ctx.param_str("controlId")?;
                ("GET", format!("{}/apis/v1/docs/{}/controls/{}", base_url, doc_id, id), None)
            }
            (r, o) => return Err(NodeError::Other(format!("coda: {}.{} not implemented", r, o))),
        };

        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!("coda: {}", e)))?;
        let status = resp.status();
        let parsed: Value = resp.json().await.unwrap_or(Value::Null);
        if !status.is_success() {
            return Err(NodeError::Http(format!("coda {}: {}", status, parsed)));
        }
        Ok(vec![vec![NodeItem { json: parsed, ..Default::default() }]])
    }
}

inventory::submit! { NodeFactory::new("coda", || Arc::new(CodaNode)) }
