#!/bin/bash
#
# CRM OAuth M2M API - cURL Examples
#
# This script demonstrates how to use the CRM M2M API with cURL.
#
# SETUP: Both endpoints are issued with your M2M credentials:
#   export OAUTH_TOKEN_ENDPOINT="{token-endpoint}"
#   export API_ENDPOINT="https://{api-base-url}"
#

set -e  # Exit on error

# Configuration - Load from environment variables (fail if missing)
: "${OAUTH_TOKEN_ENDPOINT:?Missing required env var OAUTH_TOKEN_ENDPOINT}"
: "${OAUTH_CLIENT_ID:?Missing required env var OAUTH_CLIENT_ID}"
: "${OAUTH_CLIENT_SECRET:?Missing required env var OAUTH_CLIENT_SECRET}"
: "${API_BASE_URL:?Missing required env var API_BASE_URL}"
SCOPES="${OAUTH_SCOPES:-crm-api/products.read}"

# Colors for output
GREEN='\033[0;32m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}═══════════════════════════════════════════════════════${NC}"
echo -e "${BLUE}  CRM OAuth M2M API - cURL Examples${NC}"
echo -e "${BLUE}═══════════════════════════════════════════════════════${NC}"

# ============================================================================
# STEP 1: Get Access Token
# ============================================================================

echo -e "\n${GREEN}🔐 Step 1: Obtaining access token...${NC}\n"

TOKEN_RESPONSE=$(curl -s -X POST "${OAUTH_TOKEN_ENDPOINT}" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=client_credentials" \
  -d "client_id=${OAUTH_CLIENT_ID}" \
  -d "client_secret=${OAUTH_CLIENT_SECRET}" \
  -d "scope=${SCOPES}")

# Check if token request was successful
if echo "$TOKEN_RESPONSE" | grep -q "access_token"; then
  ACCESS_TOKEN=$(echo "$TOKEN_RESPONSE" | grep -o '"access_token":"[^"]*' | sed 's/"access_token":"//')
  TOKEN_TYPE=$(echo "$TOKEN_RESPONSE" | grep -o '"token_type":"[^"]*' | sed 's/"token_type":"//')
  EXPIRES_IN=$(echo "$TOKEN_RESPONSE" | grep -o '"expires_in":[0-9]*' | sed 's/"expires_in"://')

  echo -e "${GREEN}✅ Access token obtained successfully${NC}"
  echo "Token type: $TOKEN_TYPE"
  echo "Expires in: $EXPIRES_IN seconds ($((EXPIRES_IN / 60)) minutes)"
  echo "Access token: ${ACCESS_TOKEN:0:50}..."
else
  echo -e "${RED}❌ Token request failed:${NC}"
  echo "$TOKEN_RESPONSE" | jq '.'
  exit 1
fi

# ============================================================================
# STEP 2: Get Products
# ============================================================================

echo -e "\n${GREEN}📦 Step 2: Fetching products...${NC}\n"

PRODUCTS_RESPONSE=$(curl -s -X GET "${API_BASE_URL}/products?limit=5" \
  -H "Authorization: Bearer ${ACCESS_TOKEN}")

if echo "$PRODUCTS_RESPONSE" | grep -q "products"; then
  PRODUCT_COUNT=$(echo "$PRODUCTS_RESPONSE" | grep -o '"products":\[[^]]*' | grep -o '{' | wc -l)
  echo -e "${GREEN}✅ Retrieved ${PRODUCT_COUNT} products${NC}\n"
  echo "$PRODUCTS_RESPONSE" | jq '.'
else
  echo -e "${RED}❌ Failed to fetch products:${NC}"
  echo "$PRODUCTS_RESPONSE" | jq '.'
fi

# ============================================================================
# STEP 3: Search Products
# ============================================================================

echo -e "\n${GREEN}🔍 Step 3: Searching products...${NC}\n"

SEARCH_QUERY="widget"
SEARCH_RESPONSE=$(curl -s -X GET "${API_BASE_URL}/products/search?q=${SEARCH_QUERY}" \
  -H "Authorization: Bearer ${ACCESS_TOKEN}")

if echo "$SEARCH_RESPONSE" | grep -q "products"; then
  SEARCH_COUNT=$(echo "$SEARCH_RESPONSE" | grep -o '"products":\[[^]]*' | grep -o '{' | wc -l)
  echo -e "${GREEN}✅ Found ${SEARCH_COUNT} products matching \"${SEARCH_QUERY}\"${NC}\n"
  echo "$SEARCH_RESPONSE" | jq '.'
else
  echo -e "${RED}❌ Search failed:${NC}"
  echo "$SEARCH_RESPONSE" | jq '.'
fi

# ============================================================================
# STEP 4: Get Single Product
# ============================================================================

# Extract first product ID from the products list (if available)
FIRST_PRODUCT_ID=$(echo "$PRODUCTS_RESPONSE" | grep -o '"id":"[^"]*' | head -1 | sed 's/"id":"//')

if [ -n "$FIRST_PRODUCT_ID" ]; then
  echo -e "\n${GREEN}📄 Step 4: Fetching single product (ID: ${FIRST_PRODUCT_ID})...${NC}\n"

  PRODUCT_RESPONSE=$(curl -s -X GET "${API_BASE_URL}/products/${FIRST_PRODUCT_ID}" \
    -H "Authorization: Bearer ${ACCESS_TOKEN}")

  if echo "$PRODUCT_RESPONSE" | grep -q '"id"'; then
    PRODUCT_NAME=$(echo "$PRODUCT_RESPONSE" | grep -o '"name":"[^"]*' | sed 's/"name":"//')
    echo -e "${GREEN}✅ Retrieved product: ${PRODUCT_NAME}${NC}\n"
    echo "$PRODUCT_RESPONSE" | jq '.'
  else
    echo -e "${RED}❌ Failed to fetch product:${NC}"
    echo "$PRODUCT_RESPONSE" | jq '.'
  fi
else
  echo -e "\n${BLUE}ℹ️  Skipping Step 4: No products available${NC}"
fi

# ============================================================================
# Complete
# ============================================================================

echo -e "\n${GREEN}═══════════════════════════════════════════════════════${NC}"
echo -e "${GREEN}✅ All API calls completed successfully!${NC}"
echo -e "${GREEN}═══════════════════════════════════════════════════════${NC}\n"

# ============================================================================
# Additional Examples (commented out)
# ============================================================================

# Get specific product by ID
# curl -X GET "${API_BASE_URL}/products/prod-123" \
#   -H "Authorization: Bearer ${ACCESS_TOKEN}"

# List brands (requires crm-api/brands.read)
# curl -X GET "${API_BASE_URL}/brands?limit=20" \
#   -H "Authorization: Bearer ${ACCESS_TOKEN}"

# NOTE: The M2M API is read-only. There is no POST/PUT/DELETE for products
# or brands via M2M — those require an admin web-app session and return 403
# for an M2M token. Client (customer) data is not part of this API at all:
# every /clients* route returns 403 regardless of scope, and GET
# /brands/overview is an internal pricelist-import surface that also
# returns 403 to every M2M token.

# ============================================================================
# Admin Operations (require Admin group membership and ID token)
# ============================================================================

# List all M2M clients (Admin only)
# ADMIN_ID_TOKEN="your-admin-id-token"
# curl -X GET "${API_BASE_URL}/oauth/clients" \
#   -H "Authorization: Bearer ${ADMIN_ID_TOKEN}"

# Create M2M client (Admin only)
# curl -X POST "${API_BASE_URL}/oauth/clients" \
#   -H "Authorization: Bearer ${ADMIN_ID_TOKEN}" \
#   -H "Content-Type: application/json" \
#   -d '{
#     "clientName": "My Integration",
#     "description": "Integration for external system",
#     "scopes": ["products.read", "brands.read"],
#     "expiresInDays": 365
#   }'

# Revoke M2M client (Admin only)
# curl -X DELETE "${API_BASE_URL}/oauth/clients/${CLIENT_ID}" \
#   -H "Authorization: Bearer ${ADMIN_ID_TOKEN}"
