// 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)
//
// `medium` — publish posts via the Medium API.
// Param names: resource (post/publication), operation, publication,
// publicationId, title, contentFormat, content.
// Credential `mediumApi`: { accessToken } (legacy integration 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 MediumNode;

static META: NodeMetadata = NodeMetadata {
    name: "medium",
    display_name: "Medium",
    version: &[1],
    group: &["output"],
    description: "Publish posts on Medium",
    inputs: 1,
    outputs: 1,
    properties: &[
        PropertyDef { name: "resource", display_name: "Resource", kind: PropertyKind::Options, required: true, default: Some("post") },
        PropertyDef { name: "operation", display_name: "Operation", kind: PropertyKind::Options, required: true, default: Some("create") },
        PropertyDef { name: "publication", display_name: "Publication", kind: PropertyKind::Boolean, required: false, default: Some("false") },
        PropertyDef { name: "publicationId", display_name: "Publication ID", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "title", display_name: "Title", kind: PropertyKind::String, required: false, default: None },
        PropertyDef { name: "contentFormat", display_name: "Content Format", kind: PropertyKind::Options, required: false, default: Some("markdown") },
        PropertyDef { name: "content", display_name: "Content", kind: PropertyKind::String, required: false, default: None },
    ],
    credentials: &[CredentialRef { name: "mediumApi", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let token = ctx.credential_field("accessToken")
            .or_else(|_| ctx.credential_field("access_token"))?
            .as_str().ok_or_else(|| NodeError::MissingCredential("mediumApi.accessToken".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.medium.com".to_string());
        let resource = ctx.param_opt_str("resource").unwrap_or_else(|| "post".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()) {
            ("post", "create") => {
                let title = ctx.param_str("title")?;
                let content = ctx.param_str("content")?;
                let format = ctx.param_opt_str("contentFormat").unwrap_or_else(|| "markdown".into());
                let to_publication = ctx.node_def.parameters.get("publication")
                    .and_then(|v| v.as_bool()).unwrap_or(false);
                let payload = json!({
                    "title": title,
                    "contentFormat": format,
                    "content": content,
                });
                let url = if to_publication {
                    let pub_id = ctx.param_str("publicationId")?;
                    format!("{}/v1/publications/{}/posts", base_url, pub_id)
                } else {
                    // /me first to get user id, then /users/<id>/posts. Skip
                    // the lookup hop — n8n does it inline; we expect the user
                    // to supply userId via a parameter or use publication path.
                    format!("{}/v1/me/posts", base_url)
                };
                ("POST", url, Some(payload))
            }
            ("publication", "getAll") => {
                ("GET", format!("{}/v1/users/me/publications", base_url), None)
            }
            (r, o) => return Err(NodeError::Other(format!("medium: {}.{} not implemented", r, o))),
        };

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

inventory::submit! { NodeFactory::new("medium", || Arc::new(MediumNode)) }
