#!/bin/bash

# LuckyChit - Clear Cache and Deploy (Production)
# Use this when frontend updates aren't showing due to cache

set -e

echo "🗑️  Clear Cache and Deploy - LuckyChit Frontend"
echo "================================================"
echo ""

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

echo "🧹 Step 1/6: Nuclear clean - removing all cached files..."
flutter clean
rm -rf .dart_tool
rm -rf build
rm -rf ~/.pub-cache/hosted/pub.dartlang.org/  2>/dev/null || true

echo ""
echo "📦 Step 2/6: Getting fresh dependencies..."
flutter pub get

echo ""
echo "🔨 Step 3/6: Building with cache-busting..."
# Add build-name and build-number to force cache invalidation
BUILD_NUMBER=$(date +%s)
flutter build web --release \
  --web-renderer html \
  --pwa-strategy=none \
  --build-name=1.0.$BUILD_NUMBER \
  --build-number=$BUILD_NUMBER

echo ""
echo "🗑️  Step 4/6: Stopping PM2 to clear its cache..."
pm2 stop luckychit-frontend

echo ""
echo "⏳ Step 5/6: Waiting 3 seconds for processes to stop..."
sleep 3

echo ""
echo "▶️  Step 6/6: Starting PM2 with fresh build..."
pm2 start luckychit-frontend

# Alternative: Delete and recreate if needed
# pm2 delete luckychit-frontend 2>/dev/null || true
# pm2 serve /home/luckychit/apps/chitfund/luckychit/build/web 8080 --name luckychit-frontend --spa

echo ""
echo "✅ Cache cleared and deployed!"
echo ""
echo "🌐 Test the app:"
echo "   http://192.168.8.148:8080"
echo ""
echo "🔄 If still cached in browser, do HARD REFRESH:"
echo "   Chrome/Edge: Ctrl + Shift + R (Windows) or Cmd + Shift + R (Mac)"
echo "   Firefox: Ctrl + F5 (Windows) or Cmd + Shift + R (Mac)"
echo ""
echo "💡 Or clear browser cache:"
echo "   Chrome: Settings > Privacy > Clear browsing data > Cached images"
echo ""
echo "📊 PM2 Status:"
pm2 status

