#!/bin/bash
# Verify deployment is working correctly

set -e

GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo -e "${GREEN}=== Deployment Verification ===${NC}"
echo ""

ERRORS=0

# Check services
echo "Checking services..."
for service in explorer-indexer explorer-api solacescanscout-frontend nginx postgresql; do
    if systemctl is-active --quiet $service; then
        echo -e "${GREEN}✓${NC} $service is running"
    else
        echo -e "${RED}✗${NC} $service is not running"
        ERRORS=$((ERRORS + 1))
    fi
done

# Check API
echo ""
echo "Checking API..."
if curl -s http://localhost:8080/health | grep -q "healthy"; then
    echo -e "${GREEN}✓${NC} API is healthy"
else
    echo -e "${RED}✗${NC} API health check failed"
    ERRORS=$((ERRORS + 1))
fi

# Check Frontend
echo ""
echo "Checking Frontend..."
if curl -s http://localhost:3000 | grep -q "Explorer"; then
    echo -e "${GREEN}✓${NC} Frontend is responding"
else
    echo -e "${RED}✗${NC} Frontend check failed"
    ERRORS=$((ERRORS + 1))
fi

# Check Nginx
echo ""
echo "Checking Nginx..."
if curl -s http://localhost/api/health | grep -q "healthy"; then
    echo -e "${GREEN}✓${NC} Nginx proxy is working"
else
    echo -e "${RED}✗${NC} Nginx proxy check failed"
    ERRORS=$((ERRORS + 1))
fi

# Check Database
echo ""
echo "Checking Database..."
if sudo -u postgres psql -d explorer -c "SELECT 1;" > /dev/null 2>&1; then
    echo -e "${GREEN}✓${NC} Database is accessible"
else
    echo -e "${RED}✗${NC} Database check failed"
    ERRORS=$((ERRORS + 1))
fi

# Check Elasticsearch
echo ""
echo "Checking Elasticsearch..."
if curl -s http://localhost:9200 | grep -q "cluster_name"; then
    echo -e "${GREEN}✓${NC} Elasticsearch is running"
else
    echo -e "${YELLOW}⚠${NC} Elasticsearch check failed (may not be critical)"
fi

# Check Redis
echo ""
echo "Checking Redis..."
if redis-cli ping 2>/dev/null | grep -q "PONG"; then
    echo -e "${GREEN}✓${NC} Redis is running"
else
    echo -e "${YELLOW}⚠${NC} Redis check failed (may not be critical)"
fi

# Check Cloudflare Tunnel (if installed)
echo ""
echo "Checking Cloudflare Tunnel..."
if systemctl is-active --quiet cloudflared 2>/dev/null; then
    echo -e "${GREEN}✓${NC} Cloudflare Tunnel is running"
else
    echo -e "${YELLOW}⚠${NC} Cloudflare Tunnel not running (optional)"
fi

# Summary
echo ""
if [ $ERRORS -eq 0 ]; then
    echo -e "${GREEN}✓ All critical checks passed!${NC}"
    exit 0
else
    echo -e "${RED}✗ $ERRORS critical check(s) failed${NC}"
    exit 1
fi
