// 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)
//
// `highlevel` — opportunities and contacts via GoHighLevel REST.
// Param names: resource (opportunity/contact), operation, pipelineId,
// stageId, contactIdentifier, title, status, opportunityId.
// Credential `highLevelOAuth2Api`: { access_token } (Standard or White-Label).

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

static META: NodeMetadata = NodeMetadata {
    name: "highlevel",
    display_name: "HighLevel",
    version: &[1, 2],
    group: &["output"],
    description: "Manage GoHighLevel opportunities, contacts, calendars",
    inputs: 1,
    outputs: 1,
    properties: &[
        PropertyDef { name: "resource", display_name: "Resource", kind: PropertyKind::Options, required: true, default: Some("opportunity") },
        PropertyDef { name: "operation", display_name: "Operation", kind: PropertyKind::Options, required: true, default: Some("create") },
        PropertyDef { name: "pipelineId", display_name: "Pipeline ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "stageId", display_name: "Stage ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "contactIdentifier", display_name: "Contact Identifier", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "title", display_name: "Title", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "status", display_name: "Status", kind: PropertyKind::Options, required: false, default: Some("open") },
        PropertyDef { name: "opportunityId", display_name: "Opportunity ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "contactId", display_name: "Contact ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "email", display_name: "Email", kind: PropertyKind::String, required: false, default: None },
    ],
    credentials: &[CredentialRef { name: "highLevelOAuth2Api", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let token = ctx.credential_field("access_token")
            .or_else(|_| ctx.credential_field("accessToken"))?
            .as_str().ok_or_else(|| NodeError::MissingCredential("highLevelOAuth2Api.access_token".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://services.leadconnectorhq.com".to_string());
        let resource = ctx.param_opt_str("resource").unwrap_or_else(|| "opportunity".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()) {
            ("opportunity", "create") => {
                let pipeline_id = ctx.param_str("pipelineId")?;
                let stage_id = ctx.param_str("stageId")?;
                let contact_id = ctx.param_str("contactIdentifier")?;
                let title = ctx.param_str("title")?;
                let status = ctx.param_opt_str("status").unwrap_or_else(|| "open".into());
                ("POST", format!("{}/opportunities/", base_url),
                 Some(json!({
                     "pipelineId": pipeline_id,
                     "pipelineStageId": stage_id,
                     "contactId": contact_id,
                     "name": title,
                     "status": status,
                 })))
            }
            ("opportunity", "get") => {
                let id = ctx.param_str("opportunityId")?;
                ("GET", format!("{}/opportunities/{}", base_url, id), None)
            }
            ("opportunity", "delete") => {
                let id = ctx.param_str("opportunityId")?;
                ("DELETE", format!("{}/opportunities/{}", base_url, id), None)
            }
            ("contact", "create") => {
                let email = ctx.param_str("email")?;
                ("POST", format!("{}/contacts/", base_url),
                 Some(json!({ "email": email })))
            }
            ("contact", "get") => {
                let id = ctx.param_str("contactId")?;
                ("GET", format!("{}/contacts/{}", base_url, id), None)
            }
            (r, o) => return Err(NodeError::Other(format!("highlevel: {}.{} not implemented", r, o))),
        };

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

inventory::submit! { NodeFactory::new("highlevel", || Arc::new(HighLevelNode)) }
