// 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)
//
// `freshdesk` — tickets/contacts via Freshdesk REST.
// Param names lifted from n8n source: resource, operation, requester,
// requesterIdentificationValue, subject, description, status, priority,
// ticketId.
// Credential `freshdeskApi`: { apiKey, domain }.

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

static META: NodeMetadata = NodeMetadata {
    name: "freshdesk",
    display_name: "Freshdesk",
    version: &[1],
    group: &["output"],
    description: "Read or create Freshdesk tickets and contacts",
    inputs: 1,
    outputs: 1,
    properties: &[
        PropertyDef { name: "resource", display_name: "Resource", kind: PropertyKind::Options, required: true, default: Some("ticket") },
        PropertyDef { name: "operation", display_name: "Operation", kind: PropertyKind::Options, required: true, default: Some("create") },
        PropertyDef { name: "requester", display_name: "Requester", kind: PropertyKind::Options, required: false, default: Some("email") },
        PropertyDef { name: "requesterIdentificationValue", display_name: "Requester Value", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "subject", display_name: "Subject", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "description", display_name: "Description", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "status", display_name: "Status", kind: PropertyKind::Options, required: false, default: Some("open") },
        PropertyDef { name: "priority", display_name: "Priority", kind: PropertyKind::Options, required: false, default: Some("low") },
        PropertyDef { name: "ticketId", display_name: "Ticket ID", kind: PropertyKind::String, required: false, default: None },
    ],
    credentials: &[CredentialRef { name: "freshdeskApi", required: true }],
};

fn status_code(label: &str) -> u8 {
    match label.to_lowercase().as_str() { "open" => 2, "pending" => 3, "resolved" => 4, "closed" => 5, _ => 2 }
}
fn priority_code(label: &str) -> u8 {
    match label.to_lowercase().as_str() { "low" => 1, "medium" => 2, "high" => 3, "urgent" => 4, _ => 1 }
}

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let api_key = ctx.credential_field("apiKey")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("freshdeskApi.apiKey".into()))?
            .to_string();
        let domain = ctx.credential_field("domain")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("freshdeskApi.domain".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(|| format!("https://{}.freshdesk.com", domain));
        let resource = ctx.param_opt_str("resource").unwrap_or_else(|| "ticket".into());
        let operation = ctx.param_opt_str("operation").unwrap_or_else(|| "create".into());

        let (method, url, body): (&str, String, Option<Value>) = match (resource.as_str(), operation.as_str()) {
            ("ticket", "create") => {
                let subject = ctx.param_opt_str("subject").unwrap_or_default();
                let description = ctx.param_opt_str("description").unwrap_or_default();
                let status = status_code(&ctx.param_opt_str("status").unwrap_or_else(|| "open".into()));
                let priority = priority_code(&ctx.param_opt_str("priority").unwrap_or_else(|| "low".into()));
                let requester = ctx.param_opt_str("requester").unwrap_or_else(|| "email".into());
                let req_value = ctx.param_opt_str("requesterIdentificationValue").unwrap_or_default();
                let mut payload = json!({
                    "subject": subject,
                    "description": description,
                    "status": status,
                    "priority": priority,
                });
                payload.as_object_mut().unwrap().insert(requester, Value::String(req_value));
                ("POST", format!("{}/api/v2/tickets", base_url), Some(payload))
            }
            ("ticket", "get") => {
                let id = ctx.param_str("ticketId")?;
                ("GET", format!("{}/api/v2/tickets/{}", base_url, id), None)
            }
            ("ticket", "getAll") => ("GET", format!("{}/api/v2/tickets", base_url), None),
            ("ticket", "delete") => {
                let id = ctx.param_str("ticketId")?;
                ("DELETE", format!("{}/api/v2/tickets/{}", base_url, id), None)
            }
            (r, o) => return Err(NodeError::Other(format!("freshdesk: {}.{} not implemented", r, o))),
        };

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

inventory::submit! { NodeFactory::new("freshdesk", || Arc::new(FreshdeskNode)) }
