#!/bin/bash

# Auto-fix 502 Bad Gateway errors

set -e

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

cd /home/luckychit/apps/chitfund

check_backend() {
    curl -s -o /dev/null -w "%{http_code}" http://localhost:3000/health 2>/dev/null
}

check_frontend() {
    curl -s -o /dev/null -w "%{http_code}" http://localhost:8080 2>/dev/null
}

echo "📊 Step 1/4: Checking status..."
pm2 status

echo ""
echo "🔄 Step 2/4: Restarting services..."
pm2 restart all
sleep 3

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

if [ "$(check_backend)" = "200" ]; then
    echo "✅ Backend is responding"
else
    echo "⚠️  Backend not responding, recreating..."
    cd backend
    pm2 delete luckychit-api 2>/dev/null || true
    pm2 start src/server.js --name luckychit-api
    sleep 3
fi

if [ "$(check_frontend)" = "200" ]; then
    echo "✅ Frontend is responding"
else
    echo "⚠️  Frontend not responding, recreating..."
    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
fi

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

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "📊 Final Status"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
pm2 status

echo ""
if [ "$(check_backend)" = "200" ] && [ "$(check_frontend)" = "200" ]; then
    echo "✅ SUCCESS! All services running"
    echo ""
    echo "🌐 Your site should be accessible at:"
    echo "   https://chitfund.deepteklabs.com"
else
    echo "⚠️  Some services still down"
    echo ""
    echo "🔍 Run diagnostics: ./scripts/diagnose.sh"
fi

