// 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)
//
// `sentry_io` — events/issues/projects via the Sentry REST API.
// Param names match n8n: resource, operation, organizationSlug,
// projectSlug, eventId.
// Credential `sentryIoApi`: { token } (n8n calls this "Internal Auth Token").

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

static META: NodeMetadata = NodeMetadata {
    name: "sentry_io",
    display_name: "Sentry.io",
    version: &[1],
    group: &["output"],
    description: "Read Sentry events, issues, and projects",
    inputs: 1,
    outputs: 1,
    properties: &[
        PropertyDef { name: "resource", display_name: "Resource", kind: PropertyKind::Options, required: true, default: Some("event") },
        PropertyDef { name: "operation", display_name: "Operation", kind: PropertyKind::Options, required: true, default: Some("getAll") },
        PropertyDef { name: "organizationSlug", display_name: "Organization Slug", kind: PropertyKind::String, required: true, default: None },
        PropertyDef { name: "projectSlug", display_name: "Project Slug", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "eventId", display_name: "Event ID", kind: PropertyKind::String, required: false, default: None },
    ],
    credentials: &[CredentialRef { name: "sentryIoApi", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let token = ctx.credential_field("token")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("sentryIoApi.token".into()))?
            .to_string();
        let base_url = ctx.credential_field("url").ok()
            .and_then(|v| v.as_str().map(|s| s.trim_end_matches('/').to_string()))
            .unwrap_or_else(|| "https://sentry.io".to_string());
        let resource = ctx.param_opt_str("resource").unwrap_or_else(|| "event".into());
        let operation = ctx.param_opt_str("operation").unwrap_or_else(|| "getAll".into());
        let org = ctx.param_str("organizationSlug")?;

        let url = match (resource.as_str(), operation.as_str()) {
            ("event", "getAll") => {
                let project = ctx.param_str("projectSlug")?;
                format!("{}/api/0/projects/{}/{}/events/", base_url, org, project)
            }
            ("event", "get") => {
                let project = ctx.param_str("projectSlug")?;
                let event_id = ctx.param_str("eventId")?;
                format!("{}/api/0/projects/{}/{}/events/{}/", base_url, org, project, event_id)
            }
            ("issue", "getAll") => {
                let project = ctx.param_str("projectSlug")?;
                format!("{}/api/0/projects/{}/{}/issues/", base_url, org, project)
            }
            ("project", "getAll") => format!("{}/api/0/organizations/{}/projects/", base_url, org),
            (r, o) => return Err(NodeError::Other(format!("sentry_io: unknown {}.{}", r, o))),
        };

        let resp = reqwest::Client::new().get(&url).bearer_auth(&token)
            .send().await.map_err(|e| NodeError::Http(format!("sentry_io: {}", e)))?;
        let status = resp.status();
        let parsed: Value = resp.json().await.unwrap_or(Value::Null);
        if !status.is_success() {
            return Err(NodeError::Http(format!("sentry_io {}: {}", status, parsed)));
        }
        let items = match &parsed {
            Value::Array(arr) => arr.iter().map(|j| NodeItem { json: j.clone(), ..Default::default() }).collect(),
            _ => vec![NodeItem { json: parsed, ..Default::default() }],
        };
        Ok(vec![items])
    }
}

inventory::submit! { NodeFactory::new("sentry_io", || Arc::new(SentryIoNode)) }
