#!/bin/bash

# Production Deployment Script with Database Migrations
# Run this on your cPanel server

set -e  # Exit on any error

echo "🚀 Starting production deployment..."

# 1. Backup database before any changes
echo "📦 Creating database backup..."
mysqldump -u $DB_USER -p$DB_PASSWORD $DB_NAME > backup_$(date +%Y%m%d_%H%M%S).sql

# 2. Pull latest code
echo "📥 Pulling latest code..."
git pull origin staging

# 3. Install dependencies
echo "📦 Installing dependencies..."
npm install --production

# 4. Check migration status
echo "🔍 Checking migration status..."
npx prisma migrate status

# 5. Apply pending migrations
echo "🗄️ Applying database migrations..."
npx prisma migrate deploy

# 6. Generate Prisma client
echo "⚙️ Generating Prisma client..."
npx prisma generate

# 7. Build application
echo "🏗️ Building application..."
npm run build

# 8. Restart application
echo "🔄 Restarting application..."
pm2 restart 0

echo "✅ Deployment completed successfully!"

# 9. Run health check
echo "🏥 Running health check..."
sleep 5
curl -f http://localhost:3000/api/health || echo "⚠️ Health check failed"

echo "🎉 Deployment finished!" 