// 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)
//
// `strava` — activities via the Strava v3 API.
// Param names: resource (activity), operation, name, type, startDate,
// elapsedTime, distance, activityId.
// Credential `stravaOAuth2Api`: { access_token }.

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

static META: NodeMetadata = NodeMetadata {
    name: "strava",
    display_name: "Strava",
    version: &[1],
    group: &["output"],
    description: "Read or create Strava activities",
    inputs: 1,
    outputs: 1,
    properties: &[
        PropertyDef { name: "resource", display_name: "Resource", kind: PropertyKind::Options, required: true, default: Some("activity") },
        PropertyDef { name: "operation", display_name: "Operation", kind: PropertyKind::Options, required: true, default: Some("get") },
        PropertyDef { name: "name", display_name: "Name", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "type", display_name: "Type", kind: PropertyKind::Options, required: false, default: Some("Run") },
        PropertyDef { name: "startDate", display_name: "Start Date (ISO 8601)", kind: PropertyKind::DateTime, required: false, default: None },
        PropertyDef { name: "elapsedTime", display_name: "Elapsed Time (seconds)", kind: PropertyKind::Number, required: false, default: None },
        PropertyDef { name: "distance", display_name: "Distance (meters)", kind: PropertyKind::Number, required: false, default: None },
        PropertyDef { name: "activityId", display_name: "Activity ID", kind: PropertyKind::String, required: false, default: None },
    ],
    credentials: &[CredentialRef { name: "stravaOAuth2Api", required: true }],
};

#[async_trait]
impl Node for StravaNode {
    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("stravaOAuth2Api.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://www.strava.com/api/v3".to_string());
        let operation = ctx.param_opt_str("operation").unwrap_or_else(|| "get".into());

        let (method, url, body): (&str, String, Option<Value>) = match operation.as_str() {
            "get" => {
                let id = ctx.param_str("activityId")?;
                ("GET", format!("{}/activities/{}", base_url, id), None)
            }
            "getAll" => ("GET", format!("{}/athlete/activities", base_url), None),
            "create" => {
                let name = ctx.param_str("name")?;
                let typ = ctx.param_opt_str("type").unwrap_or_else(|| "Run".into());
                let start = ctx.param_str("startDate")?;
                let elapsed = ctx.node_def.parameters.get("elapsedTime").and_then(|v| v.as_u64()).unwrap_or(0);
                let mut payload = json!({
                    "name": name,
                    "type": typ,
                    "start_date_local": start,
                    "elapsed_time": elapsed,
                });
                if let Some(d) = ctx.node_def.parameters.get("distance").and_then(|v| v.as_f64()) {
                    payload.as_object_mut().unwrap().insert("distance".into(), json!(d));
                }
                ("POST", format!("{}/activities", base_url), Some(payload))
            }
            "update" => {
                let id = ctx.param_str("activityId")?;
                let name = ctx.param_opt_str("name");
                let typ = ctx.param_opt_str("type");
                let mut payload = json!({});
                if let Some(n) = name { payload.as_object_mut().unwrap().insert("name".into(), Value::String(n)); }
                if let Some(t) = typ { payload.as_object_mut().unwrap().insert("type".into(), Value::String(t)); }
                ("PUT", format!("{}/activities/{}", base_url, id), Some(payload))
            }
            other => return Err(NodeError::Other(format!("strava: unknown operation `{}`", other))),
        };

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

fn flatten_form(v: &Value) -> Vec<(String, String)> {
    let mut out = Vec::new();
    if let Value::Object(map) = v {
        for (k, val) in map {
            let s = match val { Value::String(s) => s.clone(), other => other.to_string() };
            out.push((k.clone(), s));
        }
    }
    out
}

inventory::submit! { NodeFactory::new("strava", || Arc::new(StravaNode)) }
