#!/bin/bash
# =============================================================================
# Noor AI Partner API - cURL Examples
#
# This script provides ready-to-use cURL commands for the Partner API.
# Partners can copy and modify these examples without any development effort.
#
# HMAC signing is implemented as Bash functions - just source this file!
#
# Usage:
#   1. Set your credentials:
#      export NOORAI_API_KEY="your-api-key"
#      export NOORAI_API_SECRET="your-api-secret"  # Optional
#
#   2. Source this script:
#      source noorai-curl-examples.sh
#
#   3. Use the helper functions:
#      noorai_issue_badge "template-uuid" "user@example.com" "John" "Doe"
# =============================================================================

# Configuration
NOORAI_BASE_URL="${NOORAI_BASE_URL:-https://app.noorai.sg/api/openbadge}"

# -----------------------------------------------------------------------------
# HMAC Signing Function (handles the crypto for you!)
# -----------------------------------------------------------------------------
noorai_sign_request() {
    local payload="$1"
    local timestamp=$(date +%s)
    local message="${timestamp}.${payload}"
    
    if [[ -z "$NOORAI_API_SECRET" ]]; then
        echo ""
        return
    fi
    
    local signature=$(echo -n "$message" | openssl dgst -sha256 -hmac "$NOORAI_API_SECRET" | awk '{print $2}')
    echo "-H 'X-Signature: ${signature}' -H 'X-Timestamp: ${timestamp}'"
}

# -----------------------------------------------------------------------------
# Issue a Single Badge
# -----------------------------------------------------------------------------
noorai_issue_badge() {
    local template_id="$1"
    local recipient_email="$2"
    local recipient_given_name="$3"
    local recipient_family_name="$4"
    local narrative="${5:-}"
    local evidence_url="${6:-}"
    
    local payload=$(cat <<EOF
{
    "template_id": "${template_id}",
    "recipient_email": "${recipient_email}",
    "recipient_given_name": "${recipient_given_name}",
    "recipient_family_name": "${recipient_family_name}"
}
EOF
)
    
    # Add optional fields
    if [[ -n "$narrative" ]]; then
        payload=$(echo "$payload" | sed 's/}$/,\n    "narrative": "'$narrative'"\n}/')
    fi
    if [[ -n "$evidence_url" ]]; then
        payload=$(echo "$payload" | sed 's/}$/,\n    "evidence_url": "'$evidence_url'"\n}/')
    fi
    
    local sign_headers=$(noorai_sign_request "$payload")
    
    eval "curl -s -X POST '${NOORAI_BASE_URL}/partner/badges/' \
        -H 'Content-Type: application/json' \
        -H 'Accept: application/json' \
        -H 'X-Partner-Key: ${NOORAI_API_KEY}' \
        -H 'X-API-Key: ${NOORAI_API_KEY}' \
        ${sign_headers} \
        -d '${payload}'"
}

# -----------------------------------------------------------------------------
# List Available Templates
# -----------------------------------------------------------------------------
noorai_list_templates() {
    local sign_headers=$(noorai_sign_request "")
    
    eval "curl -s -X GET '${NOORAI_BASE_URL}/partner/templates/' \
        -H 'Accept: application/json' \
        -H 'X-Partner-Key: ${NOORAI_API_KEY}' \
        -H 'X-API-Key: ${NOORAI_API_KEY}' \
        ${sign_headers}"
}

# -----------------------------------------------------------------------------
# Get Analytics
# -----------------------------------------------------------------------------
noorai_get_analytics() {
    local period="${1:-last_30_days}"
    local sign_headers=$(noorai_sign_request "")
    
    eval "curl -s -X GET '${NOORAI_BASE_URL}/partner/analytics/?period=${period}' \
        -H 'Accept: application/json' \
        -H 'X-Partner-Key: ${NOORAI_API_KEY}' \
        -H 'X-API-Key: ${NOORAI_API_KEY}' \
        ${sign_headers}"
}

# -----------------------------------------------------------------------------
# Get Account Info
# -----------------------------------------------------------------------------
noorai_get_account() {
    local sign_headers=$(noorai_sign_request "")
    
    eval "curl -s -X GET '${NOORAI_BASE_URL}/partner/account/' \
        -H 'Accept: application/json' \
        -H 'X-Partner-Key: ${NOORAI_API_KEY}' \
        -H 'X-API-Key: ${NOORAI_API_KEY}' \
        ${sign_headers}"
}

# -----------------------------------------------------------------------------
# Revoke a Badge
# -----------------------------------------------------------------------------
noorai_revoke_badge() {
    local credential_id="$1"
    local reason="$2"
    local notify="${3:-true}"
    
    local payload=$(cat <<EOF
{
    "reason": "${reason}",
    "notify_recipient": ${notify}
}
EOF
)
    
    local sign_headers=$(noorai_sign_request "$payload")
    
    eval "curl -s -X POST '${NOORAI_BASE_URL}/partner/badges/${credential_id}/revoke/' \
        -H 'Content-Type: application/json' \
        -H 'Accept: application/json' \
        -H 'X-Partner-Key: ${NOORAI_API_KEY}' \
        -H 'X-API-Key: ${NOORAI_API_KEY}' \
        ${sign_headers} \
        -d '${payload}'"
}

# =============================================================================
# RAW CURL EXAMPLES (Copy-paste ready)
# =============================================================================

print_examples() {
cat << 'EXAMPLES'

# =============================================================================
# NOOR AI PARTNER API - CURL EXAMPLES
# =============================================================================

# 1. ISSUE A BADGE (Simple - no HMAC)
# ------------------------------------
curl -X POST 'https://app.noorai.sg/api/openbadge/partner/badges/' \
  -H 'Content-Type: application/json' \
  -H 'X-Partner-Key: YOUR_API_KEY' \
  -d '{
    "template_id": "your-template-uuid",
    "recipient_email": "recipient@example.com",
    "recipient_given_name": "John",
    "recipient_family_name": "Doe",
    "narrative": "Completed Advanced Training Program"
  }'


# 2. ISSUE A BADGE (With HMAC Signing - More Secure)
# ---------------------------------------------------
# Generate signature:
#   TIMESTAMP=$(date +%s)
#   PAYLOAD='{"template_id":"uuid","recipient_email":"test@example.com",...}'
#   SIGNATURE=$(echo -n "${TIMESTAMP}.${PAYLOAD}" | openssl dgst -sha256 -hmac "YOUR_API_SECRET" | awk '{print $2}')

curl -X POST 'https://app.noorai.sg/api/openbadge/partner/badges/' \
  -H 'Content-Type: application/json' \
  -H 'X-Partner-Key: YOUR_API_KEY' \
  -H 'X-Signature: YOUR_GENERATED_SIGNATURE' \
  -H 'X-Timestamp: YOUR_TIMESTAMP' \
  -d '{
    "template_id": "your-template-uuid",
    "recipient_email": "recipient@example.com",
    "recipient_given_name": "John",
    "recipient_family_name": "Doe"
  }'


# 3. BULK ISSUE BADGES
# --------------------
curl -X POST 'https://app.noorai.sg/api/openbadge/partner/badges/bulk/' \
  -H 'Content-Type: application/json' \
  -H 'X-Partner-Key: YOUR_API_KEY' \
  -d '{
    "template_id": "your-template-uuid",
    "recipients": [
      {"email": "alice@example.com", "given_name": "Alice", "family_name": "Smith"},
      {"email": "bob@example.com", "given_name": "Bob", "family_name": "Jones"}
    ],
    "common_narrative": "Completed Q4 Training"
  }'


# 4. LIST AVAILABLE TEMPLATES
# ---------------------------
curl -X GET 'https://app.noorai.sg/api/openbadge/partner/templates/' \
  -H 'X-Partner-Key: YOUR_API_KEY'


# 5. GET ANALYTICS
# ----------------
curl -X GET 'https://app.noorai.sg/api/openbadge/partner/analytics/?period=last_30_days' \
  -H 'X-Partner-Key: YOUR_API_KEY'


# 6. GET ACCOUNT & CREDIT BALANCE
# -------------------------------
curl -X GET 'https://app.noorai.sg/api/openbadge/partner/account/' \
  -H 'X-Partner-Key: YOUR_API_KEY'


# 7. REGISTER WEBHOOK
# -------------------
curl -X POST 'https://app.noorai.sg/api/openbadge/partner/webhooks/' \
  -H 'Content-Type: application/json' \
  -H 'X-Partner-Key: YOUR_API_KEY' \
  -d '{
    "url": "https://your-server.com/webhooks/noorai",
    "events": ["badge.issued", "badge.viewed", "credits.low"],
    "secret": "your-webhook-secret"
  }'


# 8. REVOKE A BADGE
# -----------------
curl -X POST 'https://app.noorai.sg/api/openbadge/partner/badges/CREDENTIAL_UUID/revoke/' \
  -H 'Content-Type: application/json' \
  -H 'X-Partner-Key: YOUR_API_KEY' \
  -d '{
    "reason": "Certificate expired",
    "notify_recipient": true
  }'

EXAMPLES
}

# Print usage if script is run directly
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    echo "Noor AI Partner API - cURL Helper"
    echo "=================================="
    echo ""
    echo "To use the helper functions, source this file:"
    echo "  source ${0}"
    echo ""
    echo "Then set your credentials:"
    echo "  export NOORAI_API_KEY='your-api-key'"
    echo "  export NOORAI_API_SECRET='your-api-secret'  # Optional"
    echo ""
    echo "Available functions:"
    echo "  noorai_issue_badge <template_id> <email> <first_name> <last_name> [narrative] [evidence_url]"
    echo "  noorai_list_templates"
    echo "  noorai_get_analytics [period]"
    echo "  noorai_get_account"
    echo "  noorai_revoke_badge <credential_id> <reason> [notify=true]"
    echo ""
    echo "To see raw cURL examples:"
    echo "  source ${0} && print_examples"
fi
