#!/bin/bash

# LuckyChit Production Deployment Script
# Run this script as the luckychit user to update and redeploy

set -e  # Exit on any error

echo "🚀 Starting LuckyChit Deployment..."

# Navigate to project root
cd /home/luckychit/apps/chitfund

# Save any uncommitted changes
echo "📦 Checking for local changes..."
if ! git diff-index --quiet HEAD --; then
    echo "⚠️  Local changes detected. Stashing..."
    git stash
fi

# Pull latest code
echo "📥 Pulling latest code..."
git pull origin prodnew  # or 'main' depending on your branch

# ===== BACKEND DEPLOYMENT =====
echo ""
echo "🔧 Deploying Backend..."
cd backend

# Install dependencies
echo "📦 Installing backend dependencies..."
npm install

# Restart backend with zero downtime
echo "♻️  Restarting backend API..."
pm2 reload luckychit-api

# ===== FRONTEND DEPLOYMENT =====
echo ""
echo "🎨 Deploying Frontend..."
cd ../luckychit

# Get Flutter dependencies
echo "📦 Getting Flutter dependencies..."
flutter pub get

# Build for web
echo "🏗️  Building Flutter web app with cache-busting..."
# Add timestamp to force browser cache refresh
BUILD_NUMBER=$(date +%s)
flutter build web --release --web-renderer html --pwa-strategy=none --build-number=$BUILD_NUMBER
echo "📦 Build version: $BUILD_NUMBER (Service Worker: Disabled)"

# Restart frontend
echo "♻️  Restarting frontend..."
pm2 reload luckychit-frontend

# ===== VERIFICATION =====
echo ""
echo "✅ Deployment Complete!"
echo ""
echo "📊 PM2 Status:"
pm2 status

echo ""
echo "🔍 Quick Health Check:"
echo "Backend: curl http://localhost:3000/health"
echo "Frontend: curl http://localhost:8080"
echo ""
echo "📝 View logs:"
echo "  pm2 logs luckychit-api --lines 50"
echo "  pm2 logs luckychit-frontend --lines 50"

