// 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)
//
// `pagerduty` — incidents via the PagerDuty REST v2 API.
// Param names match n8n: resource=incident, operation, title, serviceId,
// urgency, incidentKey.
// Credential `pagerDutyApi`: { apiToken }.

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

static META: NodeMetadata = NodeMetadata {
    name: "pagerduty",
    display_name: "PagerDuty",
    version: &[1],
    group: &["output"],
    description: "Read or create PagerDuty incidents",
    inputs: 1,
    outputs: 1,
    properties: &[
        PropertyDef { name: "resource", display_name: "Resource", kind: PropertyKind::Options, required: true, default: Some("incident") },
        PropertyDef { name: "operation", display_name: "Operation", kind: PropertyKind::Options, required: true, default: Some("create") },
        PropertyDef { name: "title", display_name: "Title", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "serviceId", display_name: "Service ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "urgency", display_name: "Urgency", kind: PropertyKind::Options, required: false, default: Some("high") },
        PropertyDef { name: "incidentKey", display_name: "Incident Key", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "incidentId", display_name: "Incident ID", kind: PropertyKind::String, required: false, default: None },
    ],
    credentials: &[CredentialRef { name: "pagerDutyApi", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let token = ctx.credential_field("apiToken")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("pagerDutyApi.apiToken".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.pagerduty.com".to_string());
        let operation = ctx.param_opt_str("operation").unwrap_or_else(|| "create".into());

        let (method, url, body): (&str, String, Option<Value>) = match operation.as_str() {
            "get" => {
                let id = ctx.param_str("incidentId")?;
                ("GET", format!("{}/incidents/{}", base_url, id), None)
            }
            "getAll" => ("GET", format!("{}/incidents", base_url), None),
            "create" => {
                let title = ctx.param_str("title")?;
                let service_id = ctx.param_str("serviceId")?;
                let urgency = ctx.param_opt_str("urgency").unwrap_or_else(|| "high".into());
                let incident_key = ctx.param_opt_str("incidentKey");
                let mut incident = json!({
                    "type": "incident",
                    "title": title,
                    "service": { "id": service_id, "type": "service_reference" },
                    "urgency": urgency,
                });
                if let Some(k) = incident_key {
                    incident.as_object_mut().unwrap().insert("incident_key".into(), Value::String(k));
                }
                ("POST", format!("{}/incidents", base_url), Some(json!({ "incident": incident })))
            }
            other => return Err(NodeError::Other(format!("pagerduty: unknown operation `{}`", other))),
        };

        let mut req = reqwest::Client::new().request(method.parse().unwrap(), &url)
            .header("Authorization", format!("Token token={}", token))
            .header("Accept", "application/vnd.pagerduty+json;version=2")
            .header("From", ctx.param_opt_str("fromEmail").unwrap_or_else(|| "ops@example.com".into()));
        if let Some(b) = body { req = req.json(&b); }
        let resp = req.send().await.map_err(|e| NodeError::Http(format!("pagerduty: {}", e)))?;
        let status = resp.status();
        let parsed: Value = resp.json().await.unwrap_or(Value::Null);
        if !status.is_success() {
            return Err(NodeError::Http(format!("pagerduty {}: {}", status, parsed)));
        }
        Ok(vec![vec![NodeItem { json: parsed, ..Default::default() }]])
    }
}

inventory::submit! { NodeFactory::new("pagerduty", || Arc::new(PagerDutyNode)) }
