#!/bin/bash

# Grubtech Order Receive Webhook - cURL (Testing)
#
# This example demonstrates how to test your webhook endpoint
# by simulating an order from Grubtech.
#
# Prerequisites:
# - curl command-line tool
# - openssl (for signature calculation)
#
# Replace the following placeholders:
# - {{WEBHOOK_SECRET}}: Your webhook secret

WEBHOOK_SECRET="{{WEBHOOK_SECRET}}"
WEBHOOK_URL="http://localhost:3000/webhooks/grubtech/orders"

# Example order payload
ORDER_PAYLOAD='{
  "orderId": "ord-123456",
  "partnerOrderId": "POS-789",
  "status": "pending",
  "createdAt": "2025-10-08T12:00:00Z",
  "customer": {
    "name": "John Doe",
    "phone": "+1234567890",
    "email": "john@example.com"
  },
  "delivery": {
    "type": "delivery",
    "address": "123 Main St, Apt 4B",
    "city": "Dubai",
    "instructions": "Ring doorbell twice"
  },
  "items": [
    {
      "id": "item-1",
      "name": "Spring Rolls",
      "quantity": 2,
      "price": 8.99,
      "modifiers": [
        {
          "id": "mod-1",
          "name": "Extra Sauce",
          "price": 1.50
        }
      ]
    }
  ],
  "totals": {
    "subtotal": 19.48,
    "tax": 1.95,
    "deliveryFee": 5.00,
    "total": 26.43
  },
  "payment": {
    "method": "card",
    "status": "paid"
  }
}'

# Calculate signature using HMAC-SHA256
calculate_signature() {
    local payload=$1
    echo -n "$payload" | openssl dgst -sha256 -hmac "$WEBHOOK_SECRET" | sed 's/^.* //'
}

# Test webhook endpoint
test_webhook() {
    echo "Testing webhook endpoint..."
    echo "URL: $WEBHOOK_URL"
    echo ""

    # Calculate signature
    SIGNATURE=$(calculate_signature "$ORDER_PAYLOAD")
    echo "Signature: $SIGNATURE"
    echo ""

    # Send webhook request
    RESPONSE=$(curl -s -w "\n%{http_code}" -X POST \
        "$WEBHOOK_URL" \
        -H "Content-Type: application/json" \
        -H "X-Grubtech-Signature: $SIGNATURE" \
        -d "$ORDER_PAYLOAD")

    # Extract HTTP status code and body
    HTTP_CODE=$(echo "$RESPONSE" | tail -n 1)
    BODY=$(echo "$RESPONSE" | sed '$d')

    echo "Response Code: $HTTP_CODE"
    echo "Response Body:"
    echo "$BODY" | jq '.' 2>/dev/null || echo "$BODY"

    # Check if accepted
    if [ "$HTTP_CODE" -eq 200 ]; then
        echo ""
        echo "✅ Order accepted!"
    else
        echo ""
        echo "❌ Order rejected or error occurred"
    fi
}

# Test invalid signature
test_invalid_signature() {
    echo ""
    echo "Testing invalid signature..."

    RESPONSE=$(curl -s -w "\n%{http_code}" -X POST \
        "$WEBHOOK_URL" \
        -H "Content-Type: application/json" \
        -H "X-Grubtech-Signature: invalid_signature_12345" \
        -d "$ORDER_PAYLOAD")

    HTTP_CODE=$(echo "$RESPONSE" | tail -n 1)
    BODY=$(echo "$RESPONSE" | sed '$d')

    echo "Response Code: $HTTP_CODE"
    echo "Response Body: $BODY"

    if [ "$HTTP_CODE" -eq 401 ]; then
        echo "✅ Invalid signature correctly rejected"
    else
        echo "❌ Unexpected response for invalid signature"
    fi
}

# Main execution
main() {
    # Test with valid signature
    test_webhook

    # Test with invalid signature
    test_invalid_signature
}

# Run tests
main
