// 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)
//
// `shopify` — products / orders via Shopify Admin REST API.
// Credential: shopify = { shop_domain = "yourshop.myshopify.com", access_token = "shpat_..." }

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

static META: NodeMetadata = NodeMetadata {
    name: "shopify",
    display_name: "Shopify",
    version: &[1, 2],
    group: &["output"],
    description: "Read Shopify products, orders, and customers",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[CredentialRef { name: "shopify", required: true }],
};

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

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let token = ctx.credential_field("access_token")?
            .as_str().ok_or_else(|| NodeError::MissingCredential("shopify.access_token".into()))?
            .to_string();
        let base_url = match ctx.credential_field("base_url").ok().and_then(|v| v.as_str().map(|s| s.trim_end_matches('/').to_string())) {
            Some(u) => u,
            None => {
                let domain = ctx.credential_field("shop_domain")?
                    .as_str().ok_or_else(|| NodeError::MissingCredential("shopify.shop_domain".into()))?
                    .to_string();
                format!("https://{}", domain)
            }
        };
        let resource = ctx.param_opt_str("resource").unwrap_or_else(|| "products".into());
        let api_version = ctx.param_opt_str("api_version").unwrap_or_else(|| "2024-04".into());

        let url = format!("{}/admin/api/{}/{}.json", base_url, api_version, resource);
        let resp = reqwest::Client::new()
            .get(&url)
            .header("X-Shopify-Access-Token", &token)
            .send().await.map_err(|e| NodeError::Http(format!("shopify: {}", e)))?;
        let status = resp.status();
        let parsed: Value = resp.json().await.unwrap_or(Value::Null);
        if !status.is_success() {
            return Err(NodeError::Http(format!("shopify {}: {}", status, parsed)));
        }
        Ok(vec![vec![NodeItem { json: parsed, ..Default::default() }]])
    }
}

inventory::submit! { NodeFactory::new("shopify", || Arc::new(ShopifyNode)) }
