#!/bin/sh
# This script assumes it is run from the app project root

echo "----------------------------------------"
echo "Clearing app caches..."

php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan cache:clear
php artisan twig:clear

echo "----------------------------------------"
# Install PHP dependencies if composer.json is present
if [ -f composer.json ]; then
    echo "Installing PHP dependencies..."
    composer install --no-interaction --no-dev --prefer-dist --optimize-autoloader
else
    echo "composer.json not found in $(pwd) — skipping Composer install."
fi

echo "----------------------------------------"
echo "Running migrations..."
php artisan migrate --force

echo "----------------------------------------"
echo "Syncing block definitions..."
php artisan blocks:import --all --force

echo "----------------------------------------"
echo "Publishing media manager assets..."
php artisan vendor:publish --tag=media-manager

echo "----------------------------------------"
# Setup cron jobs
if [ -f crons.sh ]; then
    echo "Installing cron jobs..."
    sh crons.sh | crontab -
else
    echo "crons.sh not found — skipping cron install."
fi

echo "----------------------------------------"
echo "Compiling frontend assets..."

# Load nvm and switch to the required Node version (.nvmrc)
export NVM_DIR="${NVM_DIR:-$HOME/.nvm}"
if [ -s "$NVM_DIR/nvm.sh" ]; then
    # shellcheck source=/dev/null
    . "$NVM_DIR/nvm.sh"
    nvm use --no-use 2>/dev/null || true
    nvm use 2>/dev/null || nvm install
else
    echo "nvm not found — using system Node $(node --version 2>/dev/null || echo 'unknown')"
    REQUIRED=$(cat .nvmrc 2>/dev/null | tr -d '[:space:]')
    CURRENT=$(node -e "process.stdout.write(process.versions.node.split('.')[0])" 2>/dev/null || echo "0")
    if [ -n "$REQUIRED" ] && [ "$CURRENT" -lt "$REQUIRED" ] 2>/dev/null; then
        echo "ERROR: Node $REQUIRED+ required (current: $CURRENT). Install nvm or upgrade Node." >&2
        exit 1
    fi
fi

npm install && npm run build

echo "----------------------------------------"
echo "Deployment complete."
echo "----------------------------------------"
