set -e

echo "=== Black Box Integration Tests ==="

# Start services
echo "Starting services..."
docker compose up -d --build

# Wait for health checks
echo "Waiting for services to be healthy..."
sleep 10

# Test API health endpoint
echo "Testing API health..."
API_HEALTH=$(curl -s -o /dev/null -w "%{http_code}" http://localhost/health)
if [ "$API_HEALTH" = "200" ]; then
    echo "✓ API health check passed"
else
    echo "✗ API health check failed with status $API_HEALTH"
    docker compose logs api
    exit 1
fi

# Test webhook endpoint (assuming POST endpoint exists)
echo "Testing webhook functionality..."
WEBHOOK_RESPONSE=$(curl -s -o /dev/null -w "%{http_code}" -X POST \
    -H "Content-Type: application/json" \
    -d '{"test":"data"}' \
    http://localhost/webhook/test || echo "000")

if [ "$WEBHOOK_RESPONSE" = "200" ] || [ "$WEBHOOK_RESPONSE" = "201" ] || [ "$WEBHOOK_RESPONSE" = "401" ]; then
    echo "✓ Webhook endpoint responsive (status: $WEBHOOK_RESPONSE)"
else
    echo "⚠ Webhook returned unexpected status: $WEBHOOK_RESPONSE (may need auth)"
fi

# Verify nginx is proxying correctly
echo "Testing nginx proxy headers..."
NGINX_CHECK=$(curl -s -I http://localhost/api/ | grep -c "X-Frame-Options: SAMEORIGIN" || true)
if [ "$NGINX_CHECK" -gt 0 ]; then
    echo "✓ Security headers present"
else
    echo "⚠ Security headers not detected"
fi

echo "=== Integration Tests Complete ==="
echo "To stop services: docker compose down"
