#!/bin/bash
# Configure API Permissions for Entra VerifiedID App Registration
# This script helps automate permission 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"; }

# Check Azure CLI
if ! command -v az &> /dev/null; then
    log_warning "Azure CLI not found"
    exit 1
fi

if ! az account show &> /dev/null; then
    log_warning "Not logged in to Azure"
    exit 1
fi

log_info "Configuring API Permissions for Entra VerifiedID..."

# Get app ID
read -p "Enter Application (Client) ID: " APP_ID

if [ -z "${APP_ID}" ]; then
    log_warning "App ID is required"
    exit 1
fi

# Verifiable Credentials Service App ID
VC_SERVICE_APP_ID="3db474b9-7a6d-4f50-afdc-70940ce1df8f"

log_info "Adding Verifiable Credentials Service permissions..."

# Note: Azure CLI doesn't support adding API permissions directly for Verifiable Credentials Service
# This requires manual steps in Azure Portal, but we can provide the exact steps

log_warning "API permissions must be configured manually in Azure Portal"
log_info "Follow these steps:"
echo ""
echo "1. Go to: https://portal.azure.com/#view/Microsoft_AAD_RegisteredApps/ApplicationMenuBlade/~/CallAnAPI/appId/${APP_ID}"
echo "2. Click 'API permissions'"
echo "3. Click 'Add a permission'"
echo "4. Select 'APIs my organization uses'"
echo "5. Search for: 'Verifiable Credentials Service' or use App ID: ${VC_SERVICE_APP_ID}"
echo "6. Select 'Application permissions'"
echo "7. Check the following permissions:"
echo "   - VerifiableCredential.Create.All"
echo "   - VerifiableCredential.Verify.All"
echo "8. Click 'Add permissions'"
echo "9. Click 'Grant admin consent for [Your Organization]'"
echo "10. Verify consent status shows 'Granted'"
echo ""

# Try to grant admin consent if possible
log_info "Attempting to grant admin consent..."
if az ad app permission admin-consent --id "${APP_ID}" 2>/dev/null; then
    log_success "Admin consent granted via CLI"
else
    log_warning "Admin consent must be granted manually in Azure Portal"
    log_info "Go to: API permissions → Grant admin consent"
fi

log_success "Permission configuration guide provided"
log_info "After completing manual steps, verify permissions:"
echo "az ad app permission list --id ${APP_ID}"

