#!/bin/bash

set -e

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "$SCRIPT_DIR" || exit 1

echo "🚀 Starting backend deployment (dash.itrain.africa)..."
echo "📂 Working directory: $(pwd)"
echo ""

if [ ! -f ".env" ]; then
    echo "⚠️  Warning: .env file not found. Make sure it exists before deployment."
    echo "   Continuing anyway..."
    echo ""
fi

echo "🧹 Cleaning up generated files before Git pull..."
[ -f "resources/js/ziggy.js" ] && rm -f "resources/js/ziggy.js" && echo "   Removed resources/js/ziggy.js"
[ -d "resources/js/actions" ] && rm -rf "resources/js/actions" && echo "   Removed resources/js/actions"
[ -d "resources/js/routes" ] && rm -rf "resources/js/routes" && echo "   Removed resources/js/routes"
[ -d "resources/js/wayfinder" ] && rm -rf "resources/js/wayfinder" && echo "   Removed resources/js/wayfinder"
echo "✅ Generated files cleaned"
echo ""

echo "🔄 Resetting local changes to match repository..."
if ! git diff --quiet || ! git diff --cached --quiet; then
    echo "   Discarding local changes..."
    git reset --hard HEAD
    echo "✅ Local changes discarded"
else
    echo "✅ No local changes detected"
fi
echo ""

echo "🔄 Pulling latest changes from Git..."
CURRENT_BRANCH=$(git branch --show-current)
if [ -z "$CURRENT_BRANCH" ]; then
    echo "❌ Error: Could not determine current Git branch"
    exit 1
fi
git pull origin "$CURRENT_BRANCH"
echo "✅ Git pull complete"
echo ""

echo "📦 Installing Composer dependencies..."
composer install --ignore-platform-reqs --no-interaction --prefer-dist --optimize-autoloader --no-dev
echo "✅ Composer dependencies installed"
echo ""

echo "📦 Installing Node dependencies with Bun..."
if ! command -v bun &> /dev/null; then
    echo "❌ Error: Bun is not installed. Please install Bun first."
    exit 1
fi
bun install
echo "✅ Bun dependencies installed"
echo ""

if [ ! -f "node_modules/.bin/vite" ] && [ ! -f "node_modules/vite/bin/vite.js" ]; then
    echo "❌ Error: Vite is not installed. Please check node_modules installation."
    exit 1
fi
echo "✅ Vite installation verified"
echo ""

if php artisan list | grep -q "ziggy:generate"; then
    echo "🗺️ Generating Ziggy routes..."
    php artisan ziggy:generate
    echo "✅ Ziggy routes generated"
    echo ""
fi

if php artisan list | grep -q "wayfinder:generate"; then
    echo "🗺️ Generating Wayfinder routes..."
    php artisan wayfinder:generate
    echo "✅ Wayfinder routes generated"
    echo ""
else
    echo "⚠️  Warning: wayfinder:generate command not found. Routes may be auto-generated by Vite plugin."
    echo ""
fi

echo "📁 Cleaning build directory..."
rm -rf public/build
mkdir -p public/build
echo "✅ Build directory cleaned and ready"
echo ""

echo "🏗️ Building frontend assets (Vite)..."
if ! bun run build; then
    echo "❌ Frontend build failed!"
    exit 1
fi

if [ ! -f "public/build/manifest.json" ]; then
    echo "❌ Error: Vite manifest file not found at public/build/manifest.json"
    echo "Build may have failed silently. Please check the build output above."
    exit 1
fi

echo "✅ Frontend build complete and manifest verified"
echo ""

echo "🔗 Checking storage symlink..."
if [ ! -L "public/storage" ]; then
    echo "   Creating storage symlink..."
    php artisan storage:link
    echo "✅ Storage symlink created"
else
    echo "✅ Storage symlink already exists"
fi
echo ""

echo "🛠️ Running database migrations..."
php artisan migrate --force
echo "✅ Migrations complete"
echo ""

echo "🧹 Clearing and optimizing Laravel caches..."
php artisan optimize:clear
php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear
php artisan event:clear

mkdir -p bootstrap/cache
chmod 775 bootstrap/cache 2>/dev/null || true

echo "⚡ Optimizing for production..."
php artisan config:cache
if ! php artisan route:cache 2>/dev/null; then
    echo "⚠️  Warning: php artisan route:cache failed."
    echo "   Clearing route cache so the app can boot. Fix: chmod 775 bootstrap/cache and run route:cache."
    php artisan route:clear
fi
php artisan view:cache
php artisan event:cache
echo "✅ Cache optimization complete"
echo ""

echo "♻️ Restarting PHP-FPM..."
PHP_VERSIONS=("php8.4-fpm" "php8.3-fpm" "php8.2-fpm" "php-fpm")
PHP_FPM_RESTARTED=false

for php_fpm in "${PHP_VERSIONS[@]}"; do
    if systemctl list-units --type=service --all | grep -q "$php_fpm"; then
        if sudo systemctl restart "$php_fpm" 2>/dev/null; then
            echo "✅ Restarted $php_fpm"
            PHP_FPM_RESTARTED=true
            break
        fi
    fi
done

if [ "$PHP_FPM_RESTARTED" = false ]; then
    echo "⚠️  Warning: Could not restart PHP-FPM. Please restart manually if needed."
fi
echo ""

echo "♻️ Restarting web server..."
if systemctl list-units --type=service --all | grep -q "nginx"; then
    if sudo systemctl restart nginx 2>/dev/null; then
        echo "✅ Restarted Nginx"
    else
        echo "⚠️  Warning: Could not restart Nginx. You may need sudo privileges."
    fi
elif systemctl list-units --type=service --all | grep -q "apache2"; then
    if sudo systemctl restart apache2 2>/dev/null; then
        echo "✅ Restarted Apache"
    else
        echo "⚠️  Warning: Could not restart Apache. You may need sudo privileges."
    fi
else
    echo "⚠️  Warning: Could not detect web server (Nginx/Apache). Please restart manually if needed."
fi
echo ""

echo "✨ Backend deployment complete! Your application is now live at https://dash.itrain.africa"
echo ""
echo "📋 Summary:"
echo "   - Git pull: ✅"
echo "   - Dependencies installed: ✅"
echo "   - Frontend built: ✅"
echo "   - Routes generated: ✅"
echo "   - Migrations run: ✅"
echo "   - Caches optimized: ✅"
echo "   - Services restarted: ✅"
