#!/bin/bash
# ─────────────────────────────────────────────────────────────────────────────
# LedgerFlow — Production Deploy Script
# Run this on your server from the project root directory
# ─────────────────────────────────────────────────────────────────────────────

set -e  # Exit on any error

echo ""
echo "🚀 LedgerFlow Deploy Script"
echo "────────────────────────────────────────"

# ─── 1. Check .env exists ─────────────────────────────────────────────────────
if [ ! -f backend/.env ]; then
  echo ""
  echo "❌ backend/.env not found!"
  echo "   Copy and fill it in first:"
  echo "   cp .env.example backend/.env"
  echo "   nano backend/.env"
  exit 1
fi
echo "✅ .env found"

# ─── 2. Install backend dependencies ─────────────────────────────────────────
echo ""
echo "📦 Installing backend dependencies..."
cd backend
npm install --omit=dev
cd ..
echo "✅ Backend deps installed"

# ─── 3. Install & build frontend ─────────────────────────────────────────────
echo ""
echo "🔨 Building frontend..."
cd frontend
npm install
npm run build
cd ..
echo "✅ Frontend built → frontend/dist/"

# ─── 4. Start/restart with PM2 ───────────────────────────────────────────────
echo ""
echo "⚙️  Starting with PM2..."

if pm2 list | grep -q "ledgerflow"; then
  pm2 restart ledgerflow
  echo "✅ PM2 process restarted"
else
  pm2 start backend/server.js --name ledgerflow
  pm2 save
  echo "✅ PM2 process started and saved"
fi

echo ""
echo "────────────────────────────────────────"
echo "✅ Deploy complete!"
echo "   Your app: https://daleib1.bgm.me"
echo "   PM2 logs: pm2 logs ledgerflow"
echo "────────────────────────────────────────"
echo ""
