#!/bin/bash
# Check AS4 Settlement System Status
# Comprehensive status check

set -e

BASE_URL="${AS4_BASE_URL:-http://localhost:3000}"

echo "========================================="
echo "AS4 Settlement System Status"
echo "========================================="
echo ""

# Check server health
echo "1. Server Health:"
curl -s "$BASE_URL/health" | jq '.' || echo "  ✗ Server not responding"
echo ""

# Check AS4 metrics
echo "2. AS4 Metrics:"
curl -s "$BASE_URL/api/v1/as4/metrics/health" | jq '.' || echo "  ✗ Metrics not available"
echo ""

# Check database tables
echo "3. Database Tables:"
if command -v psql &> /dev/null && [ -n "$DATABASE_URL" ]; then
    psql "$DATABASE_URL" -c "
    SELECT table_name 
    FROM information_schema.tables 
    WHERE table_schema = 'public' 
    AND table_name LIKE 'as4_%'
    ORDER BY table_name;
    " 2>/dev/null || echo "  ⚠ Database not accessible"
else
    echo "  ⚠ PostgreSQL not available"
fi
echo ""

# Check Redis
echo "4. Redis Status:"
if command -v redis-cli &> /dev/null; then
    if redis-cli ping &> /dev/null; then
        echo "  ✓ Redis is running"
    else
        echo "  ✗ Redis is not responding"
    fi
else
    echo "  ⚠ Redis CLI not available"
fi
echo ""

# Check certificates
echo "5. Certificates:"
if [ -f "certs/as4/as4-tls-cert.pem" ]; then
    echo "  ✓ TLS certificate exists"
    openssl x509 -noout -subject -in certs/as4/as4-tls-cert.pem 2>/dev/null || true
else
    echo "  ⚠ TLS certificate not found"
fi
echo ""

# Check routes
echo "6. Route Registration:"
if grep -q "as4GatewayRoutes" src/integration/api-gateway/app.ts 2>/dev/null; then
    echo "  ✓ Routes registered in app.ts"
else
    echo "  ✗ Routes not registered"
fi
echo ""

echo "========================================="
echo "Status Check Complete"
echo "========================================="
