// 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)
//
// `interval` — trigger node that fires once after a configured duration.
// Like `cron` but plain delay. v0.1: one-shot. Recurring is v0.2.

use async_trait::async_trait;
use crate::core::error::NodeError;
use crate::core::types::*;
use crate::engine::{ExecuteCtx, Node, NodeFactory};
use serde_json::json;
use std::sync::Arc;
use std::time::Duration;

pub struct IntervalNode;

static META: NodeMetadata = NodeMetadata {
    name: "interval",
    display_name: "Interval",
    version: &[1],
    group: &["trigger"],
    description: "Fires once after a configured duration",
    inputs: 0,
    outputs: 1,
    properties: &[],
    credentials: &[],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let secs = ctx.node_def.parameters.get("seconds")
            .and_then(|v| v.as_f64())
            .ok_or_else(|| NodeError::MissingParameter("seconds".into()))?;
        tokio::time::sleep(Duration::from_secs_f64(secs.max(0.0))).await;
        Ok(vec![vec![NodeItem {
            json: json!({ "fired_at": chrono::Utc::now().to_rfc3339() }),
            ..Default::default()
        }]])
    }
}

inventory::submit! { NodeFactory::new("interval", || Arc::new(IntervalNode)) }
