#!/bin/bash
# CI/CD Validation Script for Entra VerifiedID Deployment
# Validates code, tests, and configuration before deployment

set -euo pipefail

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

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

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

ERRORS=0

log_info "Running Entra VerifiedID Deployment Validation..."

# 1. TypeScript compilation
log_info "1. Checking TypeScript compilation..."
if pnpm build 2>&1 | grep -q "error TS"; then
    log_error "TypeScript compilation errors found"
    ((ERRORS++))
else
    log_success "TypeScript compilation passed"
fi

# 2. Linting
log_info "2. Running linter..."
if pnpm lint 2>&1 | grep -q "✖.*error"; then
    log_error "Linting errors found"
    ((ERRORS++))
else
    log_success "Linting passed"
fi

# 3. Unit tests
log_info "3. Running unit tests..."
if pnpm --filter @the-order/auth test entra-verifiedid.test.ts --run 2>&1 | grep -q "FAIL"; then
    log_error "Unit tests failed"
    ((ERRORS++))
else
    log_success "Unit tests passed"
fi

# 4. Check required files
log_info "4. 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"
    "infra/k8s/identity-service-entra-secrets.yaml"
    "infra/k8s/identity-service-deployment-entra.yaml"
)

for file in "${REQUIRED_FILES[@]}"; do
    if [ ! -f "${file}" ]; then
        log_error "Required file missing: ${file}"
        ((ERRORS++))
    fi
done

if [ ${ERRORS} -eq 0 ]; then
    log_success "All required files present"
fi

# 5. Validate Kubernetes manifests
log_info "5. Validating Kubernetes manifests..."
if command -v kubectl &> /dev/null; then
    if kubectl apply --dry-run=client -f infra/k8s/identity-service-deployment-entra.yaml &> /dev/null; then
        log_success "Kubernetes manifests are valid"
    else
        log_error "Kubernetes manifest validation failed"
        ((ERRORS++))
    fi
else
    log_info "kubectl not available, skipping manifest validation"
fi

# Summary
echo ""
if [ ${ERRORS} -eq 0 ]; then
    log_success "All validations passed! Ready for deployment."
    exit 0
else
    log_error "${ERRORS} validation error(s) found. Fix before deploying."
    exit 1
fi

