#!/bin/bash
# Comprehensive test script for all Entra VerifiedID features
# Tests issuance, verification, webhooks, retry, rate limiting, multi-manifest

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}[TEST]${NC} $1"; }
log_success() { echo -e "${GREEN}[PASS]${NC} $1"; }
log_error() { echo -e "${RED}[FAIL]${NC} $1"; }
log_warning() { echo -e "${YELLOW}[SKIP]${NC} $1"; }

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

BASE_URL="${API_BASE_URL:-http://localhost:4002}"
AUTH_TOKEN="${AUTH_TOKEN:-}"
TESTS_PASSED=0
TESTS_FAILED=0
TESTS_SKIPPED=0

# Test function
run_test() {
    local test_name=$1
    local test_command=$2
    
    log_info "Testing: ${test_name}"
    if eval "${test_command}" > /tmp/test-output.log 2>&1; then
        log_success "${test_name}"
        ((TESTS_PASSED++))
        return 0
    else
        log_error "${test_name}"
        cat /tmp/test-output.log | head -5
        ((TESTS_FAILED++))
        return 1
    fi
}

# Check if service is running
log_info "Checking if service is running..."
if ! curl -sf "${BASE_URL}/health" > /dev/null; then
    log_warning "Service not running at ${BASE_URL}"
    log_warning "Skipping API tests (unit tests will still run)"
    SKIP_API_TESTS=true
else
    SKIP_API_TESTS=false
    log_success "Service is running"
fi

echo ""
log_info "=== Running Entra VerifiedID Feature Tests ==="
echo ""

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

# 2. Credential Issuance Test
if [ "${SKIP_API_TESTS}" = "false" ]; then
    log_info "2. Testing Credential Issuance..."
    ISSUANCE_RESPONSE=$(curl -s -X POST "${BASE_URL}/vc/issue/entra" \
        -H "Content-Type: application/json" \
        ${AUTH_TOKEN:+-H "Authorization: Bearer ${AUTH_TOKEN}"} \
        -d '{"claims": {"email": "test@example.com", "name": "Test User"}}' || echo "ERROR")
    
    if echo "${ISSUANCE_RESPONSE}" | jq -e '.requestId' > /dev/null 2>&1; then
        REQUEST_ID=$(echo "${ISSUANCE_RESPONSE}" | jq -r '.requestId')
        log_success "Credential issuance successful (Request ID: ${REQUEST_ID})"
        ((TESTS_PASSED++))
    else
        log_error "Credential issuance failed"
        echo "${ISSUANCE_RESPONSE}" | head -3
        ((TESTS_FAILED++))
    fi
else
    log_warning "Skipping credential issuance test (service not running)"
    ((TESTS_SKIPPED++))
fi

# 3. Status Endpoint Test
if [ "${SKIP_API_TESTS}" = "false" ] && [ -n "${REQUEST_ID:-}" ]; then
    log_info "3. Testing Status Endpoint..."
    STATUS_RESPONSE=$(curl -s "${BASE_URL}/vc/entra/status/${REQUEST_ID}" || echo "ERROR")
    if echo "${STATUS_RESPONSE}" | jq -e '.requestId' > /dev/null 2>&1; then
        log_success "Status endpoint working"
        ((TESTS_PASSED++))
    else
        log_warning "Status endpoint test inconclusive"
        ((TESTS_SKIPPED++))
    fi
else
    log_warning "Skipping status endpoint test"
    ((TESTS_SKIPPED++))
fi

# 4. Webhook Endpoint Test
if [ "${SKIP_API_TESTS}" = "false" ]; then
    log_info "4. Testing Webhook Endpoint..."
    WEBHOOK_RESPONSE=$(curl -s -X POST "${BASE_URL}/vc/entra/webhook" \
        -H "Content-Type: application/json" \
        -d '{"requestId":"test-123","requestStatus":"issuance_successful"}' || echo "ERROR")
    
    if echo "${WEBHOOK_RESPONSE}" | jq -e '.received' > /dev/null 2>&1; then
        log_success "Webhook endpoint working"
        ((TESTS_PASSED++))
    else
        log_error "Webhook endpoint test failed"
        ((TESTS_FAILED++))
    fi
else
    log_warning "Skipping webhook endpoint test"
    ((TESTS_SKIPPED++))
fi

# 5. Multi-Manifest Test
if [ "${SKIP_API_TESTS}" = "false" ]; then
    log_info "5. Testing Multi-Manifest Support..."
    MULTI_MANIFEST_RESPONSE=$(curl -s -X POST "${BASE_URL}/vc/issue/entra" \
        -H "Content-Type: application/json" \
        ${AUTH_TOKEN:+-H "Authorization: Bearer ${AUTH_TOKEN}"} \
        -d '{"claims": {"test": "true"}, "manifestName": "diplomatic"}' || echo "ERROR")
    
    if echo "${MULTI_MANIFEST_RESPONSE}" | jq -e '.requestId' > /dev/null 2>&1; then
        log_success "Multi-manifest support working"
        ((TESTS_PASSED++))
    else
        log_warning "Multi-manifest test inconclusive (may require valid manifest)"
        ((TESTS_SKIPPED++))
    fi
else
    log_warning "Skipping multi-manifest test"
    ((TESTS_SKIPPED++))
fi

# 6. Rate Limiting Test
if [ "${SKIP_API_TESTS}" = "false" ]; then
    log_info "6. Testing Rate Limiting..."
    RATE_LIMIT_HIT=false
    for i in {1..15}; do
        HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" -X POST "${BASE_URL}/vc/issue/entra" \
            -H "Content-Type: application/json" \
            ${AUTH_TOKEN:+-H "Authorization: Bearer ${AUTH_TOKEN}"} \
            -d '{"claims": {"test": "true"}}')
        if [ "${HTTP_CODE}" = "429" ]; then
            RATE_LIMIT_HIT=true
            break
        fi
        sleep 0.1
    done
    
    if [ "${RATE_LIMIT_HIT}" = "true" ]; then
        log_success "Rate limiting working (429 received)"
        ((TESTS_PASSED++))
    else
        log_warning "Rate limit not hit (may need to adjust limits or test more aggressively)"
        ((TESTS_SKIPPED++))
    fi
else
    log_warning "Skipping rate limiting test"
    ((TESTS_SKIPPED++))
fi

# 7. Metrics Test
if [ "${SKIP_API_TESTS}" = "false" ]; then
    log_info "7. Testing Metrics Endpoint..."
    METRICS_RESPONSE=$(curl -s "${BASE_URL}/metrics" | grep -c "entra_" || echo "0")
    if [ "${METRICS_RESPONSE}" -gt 0 ]; then
        log_success "Metrics endpoint contains Entra metrics (${METRICS_RESPONSE} found)"
        ((TESTS_PASSED++))
    else
        log_warning "No Entra metrics found (may not have made requests yet)"
        ((TESTS_SKIPPED++))
    fi
else
    log_warning "Skipping metrics test"
    ((TESTS_SKIPPED++))
fi

# Summary
echo ""
log_info "=== Test Summary ==="
log_success "Passed: ${TESTS_PASSED}"
if [ ${TESTS_FAILED} -gt 0 ]; then
    log_error "Failed: ${TESTS_FAILED}"
fi
if [ ${TESTS_SKIPPED} -gt 0 ]; then
    log_warning "Skipped: ${TESTS_SKIPPED}"
fi

if [ ${TESTS_FAILED} -eq 0 ]; then
    log_success "All tests passed or skipped!"
    exit 0
else
    log_error "Some tests failed"
    exit 1
fi

