// 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)
//
// `netlify` — sites + deploys via Netlify REST.
// Param names: resource (deploy/site), operation, siteId, deployId.
// Credential `netlifyApi`: { accessToken }.

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

pub struct NetlifyNode;

static META: NodeMetadata = NodeMetadata {
    name: "netlify",
    display_name: "Netlify",
    version: &[1],
    group: &["output"],
    description: "Read Netlify sites and deploys",
    inputs: 1,
    outputs: 1,
    properties: &[
        PropertyDef { name: "resource", display_name: "Resource", kind: PropertyKind::Options, required: true, default: Some("deploy") },
        PropertyDef { name: "operation", display_name: "Operation", kind: PropertyKind::Options, required: true, default: Some("get") },
        PropertyDef { name: "siteId", display_name: "Site ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "deployId", display_name: "Deploy ID", kind: PropertyKind::String, required: false, default: None },
    ],
    credentials: &[CredentialRef { name: "netlifyApi", required: true }],
};

#[async_trait]
impl Node for NetlifyNode {
    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("netlifyApi.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://api.netlify.com".to_string());
        let resource = ctx.param_opt_str("resource").unwrap_or_else(|| "deploy".into());
        let operation = ctx.param_opt_str("operation").unwrap_or_else(|| "get".into());

        let (method, url): (&str, String) = match (resource.as_str(), operation.as_str()) {
            ("deploy", "get") => {
                let site = ctx.param_str("siteId")?;
                let deploy = ctx.param_str("deployId")?;
                ("GET", format!("{}/api/v1/sites/{}/deploys/{}", base_url, site, deploy))
            }
            ("deploy", "getAll") => {
                let site = ctx.param_str("siteId")?;
                ("GET", format!("{}/api/v1/sites/{}/deploys", base_url, site))
            }
            ("deploy", "cancel") => {
                let deploy = ctx.param_str("deployId")?;
                ("POST", format!("{}/api/v1/deploys/{}/cancel", base_url, deploy))
            }
            ("site", "get") => {
                let site = ctx.param_str("siteId")?;
                ("GET", format!("{}/api/v1/sites/{}", base_url, site))
            }
            ("site", "getAll") => ("GET", format!("{}/api/v1/sites", base_url)),
            ("site", "delete") => {
                let site = ctx.param_str("siteId")?;
                ("DELETE", format!("{}/api/v1/sites/{}", base_url, site))
            }
            (r, o) => return Err(NodeError::Other(format!("netlify: {}.{} not implemented", r, o))),
        };

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

inventory::submit! { NodeFactory::new("netlify", || Arc::new(NetlifyNode)) }
