#!/bin/bash
# Validate Entra VerifiedID Configuration
# Checks all configuration files and environment setup

set -euo pipefail

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

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[PASS]${NC} $1"; }
log_error() { echo -e "${RED}[FAIL]${NC} $1"; }
log_warning() { echo -e "${YELLOW}[WARN]${NC} $1"; }

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

ERRORS=0
WARNINGS=0

log_info "Validating Entra VerifiedID Configuration..."

# Check environment variables
log_info "Checking environment variables..."
if [ -f ".env" ]; then
    source .env 2>/dev/null || true
fi

check_var() {
    local var=$1
    local required=${2:-false}
    
    if [ -z "${!var:-}" ]; then
        if [ "${required}" = "true" ]; then
            log_error "${var} is not set (required)"
            ((ERRORS++))
        else
            log_warning "${var} is not set (optional)"
            ((WARNINGS++))
        fi
    else
        log_success "${var} is set"
    fi
}

check_var "ENTRA_TENANT_ID" true
check_var "ENTRA_CLIENT_ID" true
check_var "ENTRA_CLIENT_SECRET" true
check_var "ENTRA_CREDENTIAL_MANIFEST_ID" true
check_var "ENTRA_MANIFESTS" false
check_var "ENTRA_RATE_LIMIT_ISSUANCE" false
check_var "ENTRA_RATE_LIMIT_VERIFICATION" false

# Validate manifest JSON if set
if [ -n "${ENTRA_MANIFESTS:-}" ]; then
    log_info "Validating ENTRA_MANIFESTS JSON..."
    if echo "${ENTRA_MANIFESTS}" | jq empty 2>/dev/null; then
        log_success "ENTRA_MANIFESTS is valid JSON"
    else
        log_error "ENTRA_MANIFESTS is not valid JSON"
        ((ERRORS++))
    fi
fi

# Check required files
log_info "Checking required files..."
REQUIRED_FILES=(
    "packages/auth/src/entra-verifiedid.ts"
    "packages/auth/src/entra-verifiedid-enhanced.ts"
    "services/identity/src/entra-integration.ts"
    "services/identity/src/entra-webhooks.ts"
    "packages/monitoring/src/entra-metrics.ts"
)

for file in "${REQUIRED_FILES[@]}"; do
    if [ -f "${file}" ]; then
        log_success "Found: ${file}"
    else
        log_error "Missing: ${file}"
        ((ERRORS++))
    fi
done

# Check scripts
log_info "Checking automation scripts..."
SCRIPTS=(
    "scripts/deploy/setup-entra-automated.sh"
    "scripts/deploy/create-entra-app.sh"
    "scripts/deploy/configure-env-dev.sh"
    "scripts/test/test-entra-integration.sh"
)

for script in "${SCRIPTS[@]}"; do
    if [ -f "${script}" ] && [ -x "${script}" ]; then
        log_success "Found and executable: ${script}"
    elif [ -f "${script}" ]; then
        log_warning "Found but not executable: ${script}"
        ((WARNINGS++))
    else
        log_error "Missing: ${script}"
        ((ERRORS++))
    fi
done

# Check Kubernetes manifests
log_info "Checking Kubernetes manifests..."
K8S_FILES=(
    "infra/k8s/identity-service-entra-secrets.yaml"
    "infra/k8s/identity-service-deployment-entra.yaml"
)

for file in "${K8S_FILES[@]}"; do
    if [ -f "${file}" ]; then
        log_success "Found: ${file}"
    else
        log_warning "Missing: ${file}"
        ((WARNINGS++))
    fi
done

# Check monitoring configs
log_info "Checking monitoring configurations..."
MONITORING_FILES=(
    "infra/monitoring/prometheus-entra-config.yml"
    "infra/monitoring/grafana-entra-dashboard.json"
)

for file in "${MONITORING_FILES[@]}"; do
    if [ -f "${file}" ]; then
        log_success "Found: ${file}"
    else
        log_warning "Missing: ${file}"
        ((WARNINGS++))
    fi
done

# Test API connectivity (if service is running)
log_info "Testing API connectivity..."
if curl -sf http://localhost:4002/health > /dev/null 2>&1; then
    log_success "Identity service is running"
    
    # Test Entra endpoints
    if curl -sf http://localhost:4002/vc/issue/entra > /dev/null 2>&1; then
        log_success "Entra issuance endpoint accessible"
    else
        log_warning "Entra issuance endpoint not accessible (may require auth)"
    fi
else
    log_warning "Identity service not running locally"
fi

# Summary
echo ""
log_info "Validation Summary:"
if [ ${ERRORS} -eq 0 ]; then
    log_success "No errors found!"
else
    log_error "${ERRORS} error(s) found"
fi

if [ ${WARNINGS} -gt 0 ]; then
    log_warning "${WARNINGS} warning(s) found"
fi

if [ ${ERRORS} -eq 0 ]; then
    exit 0
else
    exit 1
fi

