#!/bin/bash

# LuckyChit Unified Deployment Script
# Usage: ./deploy.sh [backend|frontend|--force]

set -e

PROJECT_DIR="/home/luckychit/apps/chitfund"
FORCE_REBUILD=false

# Check for force flag
if [ "$1" == "--force" ] || [ "$2" == "--force" ]; then
    FORCE_REBUILD=true
fi

cd $PROJECT_DIR

echo "🚀 LuckyChit Deployment"
echo "======================="
echo ""

# Git pull
echo "📥 Pulling latest code..."
git stash 2>/dev/null || true
git pull origin prod_i8n
echo ""

# Deploy backend
if [ "$1" == "" ] || [ "$1" == "backend" ] || [ "$1" == "--force" ]; then
    echo "🔧 Deploying Backend..."
    cd $PROJECT_DIR/backend
    
    if [ "$FORCE_REBUILD" = true ]; then
        echo "🗑️  Force rebuild: Removing node_modules..."
        rm -rf node_modules package-lock.json
    fi
    
    npm install
    pm2 restart luckychit-api
    echo "✅ Backend deployed"
    echo ""
fi

# Deploy frontend
if [ "$1" == "" ] || [ "$1" == "frontend" ] || [ "$1" == "--force" ]; then
    echo "🎨 Deploying Frontend..."
    cd $PROJECT_DIR/luckychit
    
    if [ "$FORCE_REBUILD" = true ]; then
        echo "🗑️  Force rebuild: Cleaning Flutter cache..."
        flutter clean
        rm -rf .dart_tool build
    fi
    
    flutter pub get
    
    BUILD_NUMBER=$(date +%s)
    flutter build web --release --pwa-strategy=none --build-number=$BUILD_NUMBER
    echo "📦 Build version: $BUILD_NUMBER"
    
    pm2 restart luckychit-frontend
    echo "✅ Frontend deployed"
    echo ""
fi

# Status
echo "📊 PM2 Status:"
pm2 status

echo ""
echo "✅ Deployment complete!"
echo ""
echo "🧪 Test:"
echo "  Backend:  curl http://localhost:3000/health"
echo "  Frontend: curl http://localhost:8080"
echo "  Domain:   https://chitfund.deepteklabs.com"
echo ""
echo "📝 Check logs: pm2 logs --lines 20"
echo "💡 Clear browser cache: Ctrl + Shift + R"

