#!/bin/bash
# Configure development environment for Entra VerifiedID
# Generates .env file with Entra 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"; }

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

ENV_FILE=".env.entra"

log_info "Configuring development environment for Entra VerifiedID..."

# Check if .entra-app-info.txt exists
if [ -f ".entra-app-info.txt" ]; then
    log_info "Found existing app registration info"
    source <(grep -E "^(Application|Directory|Client Secret):" .entra-app-info.txt | sed 's/.*: //' | awk '{print "export " $0}')
else
    log_warning "No app registration info found. Run ./scripts/deploy/create-entra-app.sh first"
    read -p "Enter Tenant ID: " ENTRA_TENANT_ID
    read -p "Enter Client ID: " ENTRA_CLIENT_ID
    read -sp "Enter Client Secret: " ENTRA_CLIENT_SECRET
    echo
fi

read -p "Enter Credential Manifest ID (or press Enter to skip): " ENTRA_CREDENTIAL_MANIFEST_ID

# Create .env.entra file
cat > "${ENV_FILE}" << EOF
# Microsoft Entra VerifiedID Configuration
# Generated: $(date)

ENTRA_TENANT_ID=${ENTRA_TENANT_ID}
ENTRA_CLIENT_ID=${ENTRA_CLIENT_ID}
ENTRA_CLIENT_SECRET=${ENTRA_CLIENT_SECRET}
ENTRA_CREDENTIAL_MANIFEST_ID=${ENTRA_CREDENTIAL_MANIFEST_ID:-}

# Multi-manifest support (JSON format)
# ENTRA_MANIFESTS='{"default":"manifest-id-1","diplomatic":"manifest-id-2","judicial":"manifest-id-3"}'

# Entra Rate Limiting (optional)
ENTRA_RATE_LIMIT_ISSUANCE=10
ENTRA_RATE_LIMIT_VERIFICATION=20
ENTRA_RATE_LIMIT_STATUS_CHECK=30
ENTRA_RATE_LIMIT_GLOBAL=50
EOF

log_success "Environment file created: ${ENV_FILE}"
log_info "To use this configuration, run: source ${ENV_FILE}"

# Check if .env exists and offer to merge
if [ -f ".env" ]; then
    read -p "Merge with existing .env file? (y/n): " MERGE
    if [ "${MERGE}" = "y" ]; then
        cat "${ENV_FILE}" >> .env
        log_success "Merged into .env file"
    fi
fi

log_success "Development environment configured!"

