#!/bin/bash

# LOOPUMAN ONE-COMMAND DEPLOYMENT
# Uploads and starts everything

echo "🚀 LOOPUMAN DEPLOYMENT"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

# Check .env exists
if [ ! -f .env ]; then
  echo "❌ .env file not found!"
  echo "📝 Copy .env.example to .env and configure it first"
  exit 1
fi

echo "1️⃣  Installing dependencies..."
npm install
if [ $? -ne 0 ]; then
  echo "❌ npm install failed"
  exit 1
fi
echo "✅ Dependencies installed"
echo ""

echo "2️⃣  Running database migrations..."
if [ -f database/schema.sql ]; then
  echo "📝 Run this in Supabase SQL Editor:"
  echo "   - database/schema.sql"
  echo "   - reviews-system.sql"
  echo ""
  read -p "Press Enter when migrations are complete..."
fi
echo "✅ Database ready"
echo ""

echo "3️⃣  Stopping existing services..."
pm2 delete all 2>/dev/null
echo "✅ Services stopped"
echo ""

echo "4️⃣  Starting all services..."
pm2 start ecosystem.config.js
if [ $? -ne 0 ]; then
  echo "❌ PM2 start failed"
  exit 1
fi
echo "✅ Services started"
echo ""

echo "5️⃣  Saving PM2 configuration..."
pm2 save
echo "✅ PM2 saved"
echo ""

echo "6️⃣  Checking service status..."
pm2 list
echo ""

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "✅ DEPLOYMENT COMPLETE!"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "📝 Next steps:"
echo "   1. Run: ./test-everything.sh"
echo "   2. Run: ./add-test-credits.sh"
echo "   3. Test WhatsApp: Message +254702632772"
echo "   4. Test Telegram: /start @Loopuman_bot"
echo ""
echo "🔍 Monitor logs: pm2 logs"
echo "📊 Check status: pm2 status"
echo ""
