#!/bin/bash

echo "🚀 Starting backend with SMTP fix..."
echo ""

# Kill any existing backend
lsof -ti:4000 | xargs -r kill -9 2>/dev/null || true
sleep 2

# Start backend
npm run dev > /tmp/backend-startup.log 2>&1 &
BACKEND_PID=$!

echo "Backend started (PID: $BACKEND_PID)"
echo "Waiting 15 seconds for initialization..."
sleep 15

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "📋 Backend Startup Logs:"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
tail -30 /tmp/backend-startup.log
echo ""

# Check for SMTP initialization
if grep -q "Email adapter initialized" /tmp/backend-startup.log; then
    echo "✅ Email adapter initialized successfully!"
    echo ""
    grep "Email adapter initialized" /tmp/backend-startup.log
    echo ""
else
    echo "❌ Email adapter NOT initialized - check logs above"
    echo ""
fi

# Check for errors
if grep -qi "error" /tmp/backend-startup.log | head -5; then
    echo "⚠️  Errors found in logs:"
    grep -i "error" /tmp/backend-startup.log | head -5
    echo ""
fi

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "Backend is running. To test email:"
echo "  node test-smtp-simple.js"
echo ""
echo "To see live logs:"
echo "  tail -f /tmp/backend-startup.log"
echo ""
echo "To stop backend:"
echo "  kill $BACKEND_PID"
echo ""
