#!/bin/bash

# Automatic 502 Error Fix Script
# Tries common fixes for Bad Gateway errors

set -e

echo "🔧 LuckyChit 502 Auto-Fix"
echo "========================="
echo ""

# Function to check if backend is responding
check_backend() {
    RESPONSE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:3000/health 2>/dev/null)
    [ "$RESPONSE" = "200" ]
}

# Function to check if frontend is responding
check_frontend() {
    RESPONSE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:8080 2>/dev/null)
    [ "$RESPONSE" = "200" ]
}

echo "📊 Step 1/6: Checking current status..."
pm2 status

echo ""
echo "🔄 Step 2/6: Attempting PM2 restart..."
pm2 restart all

sleep 3

echo ""
echo "🧪 Step 3/6: Testing services..."

# Test backend
if check_backend; then
    echo "✅ Backend is responding"
else
    echo "⚠️  Backend not responding, trying to start..."
    cd /home/luckychit/apps/chitfund/backend
    pm2 delete luckychit-api 2>/dev/null || true
    pm2 start src/server.js --name luckychit-api
    sleep 3
    
    if check_backend; then
        echo "✅ Backend started successfully"
    else
        echo "❌ Backend still not responding"
        echo "Check logs: pm2 logs luckychit-api"
    fi
fi

# Test frontend
if check_frontend; then
    echo "✅ Frontend is responding"
else
    echo "⚠️  Frontend not responding, trying to start..."
    cd /home/luckychit/apps/chitfund/luckychit
    pm2 delete luckychit-frontend 2>/dev/null || true
    pm2 serve build/web 8080 --name luckychit-frontend --spa
    sleep 3
    
    if check_frontend; then
        echo "✅ Frontend started successfully"
    else
        echo "❌ Frontend still not responding"
        echo "May need to rebuild: flutter build web --release"
    fi
fi

echo ""
echo "💾 Step 4/6: Saving PM2 configuration..."
pm2 save

echo ""
echo "🔥 Step 5/6: Checking firewall..."
sudo ufw status | grep -E '(3000|8080)' || {
    echo "⚠️  Firewall rules may be missing, adding..."
    sudo ufw allow 3000/tcp
    sudo ufw allow 8080/tcp
    sudo ufw reload
    echo "✅ Firewall rules added"
}

echo ""
echo "📊 Step 6/6: Final status check..."
pm2 status

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "🧪 Testing Services"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

# Test backend
if check_backend; then
    echo "✅ Backend: http://localhost:3000/health"
    curl -s http://localhost:3000/health | head -n 3
else
    echo "❌ Backend: Not responding"
fi

echo ""

# Test frontend
if check_frontend; then
    echo "✅ Frontend: http://localhost:8080"
else
    echo "❌ Frontend: Not responding"
fi

echo ""

# Test external access
EXTERNAL=$(curl -s -o /dev/null -w "%{http_code}" http://192.168.8.148:3000/health 2>/dev/null)
if [ "$EXTERNAL" = "200" ]; then
    echo "✅ External access: http://192.168.8.148:3000"
else
    echo "❌ External access: Not accessible (may be firewall)"
fi

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

# Final verdict
if check_backend && check_frontend; then
    echo "✅ SUCCESS! Both services are running"
    echo ""
    echo "🌐 Your site should now be accessible at:"
    echo "   https://chitfund.deepteklabs.com"
    echo ""
    echo "💡 If still showing 502, wait 1-2 minutes for Cloudflare to detect"
    echo "   Or purge Cloudflare cache in dashboard"
else
    echo "⚠️  WARNING: Some services are still down"
    echo ""
    echo "🔍 Next steps:"
    echo "   1. Check logs: pm2 logs"
    echo "   2. Check database: sudo systemctl status postgresql"
    echo "   3. Run full diagnostic: ./diagnose-502.sh"
    echo "   4. See detailed guide: FIX_502_ERROR.md"
fi

echo ""

