#!/bin/bash
# Test Entra VerifiedID Integration
# Runs all integration tests for Entra VerifiedID

set -euo pipefail

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

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

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

log_info "Running Entra VerifiedID Integration Tests..."

# Check if environment variables are set
if [ -z "${ENTRA_TENANT_ID:-}" ] || [ -z "${ENTRA_CLIENT_ID:-}" ] || [ -z "${ENTRA_CLIENT_SECRET:-}" ]; then
    log_error "Entra environment variables not set"
    log_info "Set: ENTRA_TENANT_ID, ENTRA_CLIENT_ID, ENTRA_CLIENT_SECRET"
    exit 1
fi

# Run unit tests
log_info "Running unit tests..."
if pnpm --filter @the-order/auth test entra-verifiedid.test.ts 2>&1 | tee /tmp/entra-unit-test.log; then
    log_success "Unit tests passed"
else
    log_error "Unit tests failed"
    exit 1
fi

# Run integration tests (if credentials are available)
if [ -n "${ENTRA_CREDENTIAL_MANIFEST_ID:-}" ]; then
    log_info "Running integration tests..."
    if pnpm --filter @the-order/auth test entra-verifiedid.integration.test.ts 2>&1 | tee /tmp/entra-integration-test.log; then
        log_success "Integration tests passed"
    else
        log_warning "Integration tests failed (may require valid Entra credentials)"
    fi
else
    log_info "Skipping integration tests (ENTRA_CREDENTIAL_MANIFEST_ID not set)"
fi

# Test API endpoints (if service is running)
log_info "Testing API endpoints..."
BASE_URL="${API_BASE_URL:-http://localhost:4002}"

# Test health endpoint
if curl -sf "${BASE_URL}/health" > /dev/null; then
    log_success "Service is running"
    
    # Test issuance endpoint (will fail without valid credentials, but tests endpoint exists)
    if curl -sf -X POST "${BASE_URL}/vc/issue/entra" \
        -H "Content-Type: application/json" \
        -d '{"claims": {"test": "true"}}' > /dev/null 2>&1; then
        log_success "Issuance endpoint accessible"
    else
        log_info "Issuance endpoint exists (authentication may be required)"
    fi
    
    # Test webhook endpoint
    if curl -sf -X POST "${BASE_URL}/vc/entra/webhook" \
        -H "Content-Type: application/json" \
        -d '{"requestId":"test","requestStatus":"issuance_successful"}' > /dev/null 2>&1; then
        log_success "Webhook endpoint accessible"
    else
        log_info "Webhook endpoint exists"
    fi
else
    log_info "Service not running locally, skipping API endpoint tests"
fi

log_success "All automated tests completed!"
log_info "Review test logs in /tmp/entra-*.log"

