#!/bin/bash
# Configure Webhook URL in Entra VerifiedID
# Provides instructions and validates webhook configuration

set -euo pipefail

GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
log_warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; }

log_info "Entra VerifiedID Webhook URL Configuration"
echo ""

read -p "Environment (staging/production): " ENV
ENV=${ENV:-staging}

if [ "${ENV}" = "production" ]; then
    WEBHOOK_URL="https://api.theorder.org/vc/entra/webhook"
    APP_ID_PROMPT="Production App Registration"
else
    WEBHOOK_URL="https://api-staging.theorder.org/vc/entra/webhook"
    APP_ID_PROMPT="Staging App Registration"
fi

read -p "Application (Client) ID for ${APP_ID_PROMPT}: " APP_ID

log_info "Webhook Configuration Instructions:"
echo ""
echo "1. Go to Azure Portal → Verified ID"
echo "2. Click on your credential manifest"
echo "3. Go to 'Settings' or 'Configuration'"
echo "4. Find 'Callback URL' or 'Webhook URL' section"
echo "5. Enter the following URL:"
echo ""
echo "   ${WEBHOOK_URL}"
echo ""
echo "6. Save the configuration"
echo ""

# Test webhook endpoint
log_info "Testing webhook endpoint..."
if curl -sf -X POST "${WEBHOOK_URL}" \
    -H "Content-Type: application/json" \
    -d '{"requestId":"test","requestStatus":"issuance_successful"}' > /dev/null; then
    log_success "Webhook endpoint is accessible"
else
    log_warning "Webhook endpoint test failed (may require authentication or service not deployed)"
fi

# Generate webhook test payload
cat > webhook-test-payload.json << EOF
{
  "requestId": "test-request-$(date +%s)",
  "requestStatus": "issuance_successful",
  "credential": {
    "id": "vc:test:123",
    "type": ["VerifiableCredential"],
    "issuer": "did:web:${APP_ID}.verifiedid.msidentity.com",
    "issuanceDate": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
    "credentialSubject": {
      "email": "test@example.com"
    },
    "proof": {
      "type": "JsonWebSignature2020",
      "created": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
      "proofPurpose": "assertionMethod",
      "verificationMethod": "did:web:${APP_ID}#key",
      "jws": "test-signature"
    }
  }
}
EOF

log_success "Webhook test payload created: webhook-test-payload.json"
log_info "You can test the webhook with:"
echo "curl -X POST ${WEBHOOK_URL} -H 'Content-Type: application/json' -d @webhook-test-payload.json"

