#!/bin/bash
# Configure Multi-Manifest Support for Entra VerifiedID
# Helps set up multiple credential manifests

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"; }

cd "$(dirname "$0")/../.."

log_info "Configuring Multi-Manifest Support for Entra VerifiedID..."

echo "Enter manifest IDs (press Enter to skip optional ones):"
echo ""

read -p "Default Manifest ID (required): " DEFAULT_MANIFEST
if [ -z "${DEFAULT_MANIFEST}" ]; then
    log_warning "Default manifest ID is required"
    exit 1
fi

read -p "Diplomatic Manifest ID (optional): " DIPLOMATIC_MANIFEST
read -p "Judicial Manifest ID (optional): " JUDICIAL_MANIFEST
read -p "Financial Manifest ID (optional): " FINANCIAL_MANIFEST

# Build JSON object
MANIFESTS_JSON="{"
MANIFESTS_JSON+="\"default\":\"${DEFAULT_MANIFEST}\""

if [ -n "${DIPLOMATIC_MANIFEST}" ]; then
    MANIFESTS_JSON+=",\"diplomatic\":\"${DIPLOMATIC_MANIFEST}\""
fi

if [ -n "${JUDICIAL_MANIFEST}" ]; then
    MANIFESTS_JSON+=",\"judicial\":\"${JUDICIAL_MANIFEST}\""
fi

if [ -n "${FINANCIAL_MANIFEST}" ]; then
    MANIFESTS_JSON+=",\"financial\":\"${FINANCIAL_MANIFEST}\""
fi

MANIFESTS_JSON+="}"

log_info "Generated manifest configuration:"
echo "${MANIFESTS_JSON}" | jq '.'

# Update .env file if it exists
if [ -f ".env" ]; then
    read -p "Update .env file? (y/n): " UPDATE_ENV
    if [ "${UPDATE_ENV}" = "y" ]; then
        # Remove old ENTRA_MANIFESTS if exists
        sed -i '/^ENTRA_MANIFESTS=/d' .env
        # Add new one
        echo "ENTRA_MANIFESTS='${MANIFESTS_JSON}'" >> .env
        log_success "Updated .env file"
    fi
fi

# For Kubernetes
read -p "Generate Kubernetes secret update? (y/n): " GEN_K8S
if [ "${GEN_K8S}" = "y" ]; then
    K8S_SECRET="infra/k8s/entra-manifests-secret.yaml"
    cat > "${K8S_SECRET}" << EOF
apiVersion: v1
kind: Secret
metadata:
  name: entra-manifests
  namespace: the-order-prod
type: Opaque
stringData:
  ENTRA_MANIFESTS: '${MANIFESTS_JSON}'
EOF
    log_success "Kubernetes secret created: ${K8S_SECRET}"
fi

# For Key Vault
read -p "Store in Azure Key Vault? (y/n): " STORE_KV
if [ "${STORE_KV}" = "y" ]; then
    read -p "Key Vault name: " KV_NAME
    if [ -n "${KV_NAME}" ]; then
        az keyvault secret set \
            --vault-name "${KV_NAME}" \
            --name "entra-manifests" \
            --value "${MANIFESTS_JSON}" \
            --output none
        log_success "Stored in Key Vault: ${KV_NAME}"
    fi
fi

log_success "Multi-manifest configuration complete!"
log_info "To use in code:"
echo "  const manifests = JSON.parse(process.env.ENTRA_MANIFESTS);"
echo "  await client.issueCredential({ claims: {...}, manifestName: 'diplomatic' });"

