#!/bin/bash
set -e

echo "🔍 Checking for test routes in production environment..."

# Check if APP_ENV is production
if [ "$APP_ENV" != "production" ]; then
    echo "✅ Not production environment ($APP_ENV), skipping test route check"
    exit 0
fi

echo "🚨 Production environment detected - checking for test routes..."

# Function to check routes and return non-zero if test routes are found
check_routes() {
    local route_output
    route_output=$(php artisan route:list --name="__test" 2>/dev/null || true)
    
    # Check if any test routes are registered
    if echo "$route_output" | grep -q "POST.*__test" || echo "$route_output" | grep -q "GET.*__test"; then
        echo "❌ CRITICAL: Test routes found in production!"
        echo "$route_output"
        echo ""
        echo "Test routes detected:"
        echo "$route_output" | grep "__test" || true
        echo ""
        echo "These routes expose sensitive testing functionality and must not be available in production."
        return 1
    fi
    
    return 0
}

# Check for test routes
if ! check_routes; then
    echo ""
    echo "💥 BLOCKING DEPLOYMENT: Test routes are accessible in production environment"
    echo ""
    echo "To fix this issue:"
    echo "1. Ensure test routes are properly guarded with 'test.env' middleware"
    echo "2. Verify APP_ENV=production is set correctly"
    echo "3. Check that TestEnvironmentGuard middleware is working"
    echo ""
    exit 1
fi

echo "✅ No test routes found in production - deployment safety check passed"

# Additional check: Try to access test endpoints (if we have a running server)
if command -v curl >/dev/null 2>&1; then
    echo ""
    echo "🌐 Testing HTTP access to test endpoints..."
    
    # Try to access a test endpoint
    if response=$(curl -s -o /dev/null -w "%{http_code}" "http://localhost:8000/__test/state" 2>/dev/null); then
        if [ "$response" = "404" ]; then
            echo "✅ Test endpoints return 404 as expected"
        else
            echo "❌ CRITICAL: Test endpoint returned $response instead of 404"
            echo "Test routes may be accessible in production!"
            exit 1
        fi
    else
        echo "ℹ️  Could not test HTTP endpoints (server not running)"
    fi
fi

echo ""
echo "🎉 Production environment safety checks completed successfully"
