#!/usr/bin/env bash
#
# Affiliate Aggregator — cURL examples (sample).
# API key + HMAC-SHA256 signing. Uses FAKE credentials from env vars.
#
#   export AFF_BASE_URL="http://localhost:4100/api"
#   export AFF_API_KEY="ak_test_xxx"
#   export AFF_API_SECRET="sk_test_xxx"   # shown ONCE at key creation
#
# Requires bash + openssl + curl.
set -euo pipefail

BASE_URL="${AFF_BASE_URL:-http://localhost:4100/api}"
API_KEY="${AFF_API_KEY:-ak_test_example}"
API_SECRET="${AFF_API_SECRET:-sk_test_example_secret}"

# sign <path> <json-body> [extra curl args...]
# Signs "${ts}.${body}" with HMAC-SHA256 (hex) and POSTs it.
send() {
  local path="$1"; shift
  local body="$1"; shift
  local ts sig
  ts="$(date +%s)"
  sig="$(printf '%s' "${ts}.${body}" | openssl dgst -sha256 -hmac "$API_SECRET" | sed 's/^.* //')"
  curl -sS -X POST "${BASE_URL}${path}" \
    -H "Content-Type: application/json" \
    -H "X-API-Key: ${API_KEY}" \
    -H "X-Timestamp: ${ts}" \
    -H "X-Signature: ${sig}" \
    -H "X-Request-ID: $(uuidgen 2>/dev/null || echo req-$ts)" \
    "$@" \
    --data "$body"
  echo
}

echo "== Upsert product =="
send "/v1/products/upsert" \
  '{"products":[{"externalProductId":"SKU-100","name":"Wireless Earbuds","productUrl":"https://merchant-store.com/p/sku-100","price":"2999.00","currency":"NPR","commissionType":"PERCENTAGE","commissionValue":"10"}]}' \
  -H "X-Idempotency-Key: upsert-sku-100-2026-06-14"

echo "== Report conversion (send the captured click_id) =="
send "/v1/conversions" \
  '{"clickId":"CLK_example123","externalOrderId":"ORD-1001","externalProductId":"SKU-100","orderAmount":"2999.00","currency":"NPR","orderStatus":"confirmed"}' \
  -H "X-Idempotency-Key: ORD-1001-conversion"

echo "== Update order status =="
send "/v1/order-status" \
  '{"externalOrderId":"ORD-1001","status":"delivered"}' \
  -H "X-Idempotency-Key: ORD-1001-delivered"

echo "== Webhook: order-created (X-External-Event-Id is REQUIRED) =="
send "/v1/webhooks/order-created" \
  '{"click_id":"CLK_example123","external_order_id":"ORD-1001","order_amount":"2999.00","currency":"NPR"}' \
  -H "X-External-Event-Id: evt-ORD-1001-created"
