#!/bin/bash
# Verify Complete Entra VerifiedID Setup
# Comprehensive validation of all setup steps

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}[VERIFY]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_error() { echo -e "${RED}[✗]${NC} $1"; }
log_warning() { echo -e "${YELLOW}[!]${NC} $1"; }

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

CHECKS_PASSED=0
CHECKS_FAILED=0
CHECKS_WARNING=0

check() {
    local name=$1
    local command=$2
    
    log_info "Checking: ${name}"
    if eval "${command}" > /dev/null 2>&1; then
        log_success "${name}"
        ((CHECKS_PASSED++))
        return 0
    else
        log_error "${name}"
        ((CHECKS_FAILED++))
        return 1
    fi
}

check_warning() {
    local name=$1
    local command=$2
    
    log_info "Checking: ${name}"
    if eval "${command}" > /dev/null 2>&1; then
        log_success "${name}"
        ((CHECKS_PASSED++))
        return 0
    else
        log_warning "${name} (optional)"
        ((CHECKS_WARNING++))
        return 1
    fi
}

echo ""
log_info "=== Entra VerifiedID Complete Setup Verification ==="
echo ""

# 1. Code Files
log_info "1. Code Implementation"
check "Entra VerifiedID client exists" "[ -f packages/auth/src/entra-verifiedid.ts ]"
check "Enhanced client exists" "[ -f packages/auth/src/entra-verifiedid-enhanced.ts ]"
check "Integration exists" "[ -f services/identity/src/entra-integration.ts ]"
check "Webhook handler exists" "[ -f services/identity/src/entra-webhooks.ts ]"
check "Metrics exist" "[ -f packages/monitoring/src/entra-metrics.ts ]"

# 2. Tests
log_info "2. Test Suite"
check "Unit tests exist" "[ -f packages/auth/src/entra-verifiedid.test.ts ]"
check "Integration tests exist" "[ -f packages/auth/src/entra-verifiedid.integration.test.ts ]"

# 3. Scripts
log_info "3. Automation Scripts"
check "Setup script exists" "[ -f scripts/deploy/setup-entra-automated.sh ]"
check "App creation script exists" "[ -f scripts/deploy/create-entra-app.sh ]"
check "Deployment scripts exist" "[ -f scripts/deploy/deploy-staging.sh ]"
check "Test scripts exist" "[ -f scripts/test/test-all-entra-features.sh ]"
check "Validation script exists" "[ -f scripts/validation/validate-entra-config.sh ]"

# 4. Configuration
log_info "4. Configuration Files"
check "Kubernetes secrets template exists" "[ -f infra/k8s/identity-service-entra-secrets.yaml ]"
check "Kubernetes deployment exists" "[ -f infra/k8s/identity-service-deployment-entra.yaml ]"
check "Prometheus config exists" "[ -f infra/monitoring/prometheus-entra-config.yml ]"
check "Grafana dashboard exists" "[ -f infra/monitoring/grafana-entra-dashboard.json ]"

# 5. Documentation
log_info "5. Documentation"
check "Deployment checklist exists" "[ -f docs/deployment/ENTRA_VERIFIEDID_DEPLOYMENT_CHECKLIST.md ]"
check "Runbook exists" "[ -f docs/operations/ENTRA_VERIFIEDID_RUNBOOK.md ]"
check "Training materials exist" "[ -f docs/training/ENTRA_VERIFIEDID_TRAINING.md ]"

# 6. Environment Variables (warnings if not set)
log_info "6. Environment Configuration"
if [ -f ".env" ]; then
    source .env 2>/dev/null || true
fi

check_warning "ENTRA_TENANT_ID is set" "[ -n \"\${ENTRA_TENANT_ID:-}\" ]"
check_warning "ENTRA_CLIENT_ID is set" "[ -n \"\${ENTRA_CLIENT_ID:-}\" ]"
check_warning "ENTRA_CLIENT_SECRET is set" "[ -n \"\${ENTRA_CLIENT_SECRET:-}\" ]"
check_warning "ENTRA_CREDENTIAL_MANIFEST_ID is set" "[ -n \"\${ENTRA_CREDENTIAL_MANIFEST_ID:-}\" ]"

# 7. Build Status
log_info "7. Build Status"
if pnpm build 2>&1 | grep -q "error TS"; then
    log_error "TypeScript build has errors"
    ((CHECKS_FAILED++))
else
    log_success "TypeScript build passes"
    ((CHECKS_PASSED++))
fi

# 8. Test Execution
log_info "8. Test Execution"
if pnpm --filter @the-order/auth test entra-verifiedid.test.ts --run 2>&1 | grep -q "FAIL"; then
    log_error "Unit tests have failures"
    ((CHECKS_FAILED++))
else
    log_success "Unit tests pass"
    ((CHECKS_PASSED++))
fi

# Summary
echo ""
log_info "=== Verification Summary ==="
log_success "Passed: ${CHECKS_PASSED}"
if [ ${CHECKS_FAILED} -gt 0 ]; then
    log_error "Failed: ${CHECKS_FAILED}"
fi
if [ ${CHECKS_WARNING} -gt 0 ]; then
    log_warning "Warnings: ${CHECKS_WARNING}"
fi

TOTAL=$((CHECKS_PASSED + CHECKS_FAILED + CHECKS_WARNING))
PERCENTAGE=$((CHECKS_PASSED * 100 / TOTAL))

echo ""
if [ ${CHECKS_FAILED} -eq 0 ]; then
    log_success "All critical checks passed! (${PERCENTAGE}%)"
    if [ ${CHECKS_WARNING} -gt 0 ]; then
        log_warning "Some optional checks need attention"
    fi
    exit 0
else
    log_error "Some critical checks failed (${PERCENTAGE}%)"
    exit 1
fi

