#!/usr/bin/env bash
# Post-Deployment Script
# Usage: ./scripts/post-deploy.sh
#
# Executes post-deploy tasks in the correct order for minimal disruption.
# Cache is rebuilt BEFORE old caches are cleared to avoid a window where
# cached configs are missing.
# Reference: CLAUDE.md § Deployment Rules

set -euo pipefail

echo ""
echo "=== RankWiz Post-Deploy ==="
echo ""

# Step 1: Run database migrations
echo "[1/8] Running migrations..."
php artisan migrate --force

# Step 2: Build new caches BEFORE clearing old ones
# This minimizes the window where requests hit uncached config/routes.
echo "[2/8] Building config cache..."
php artisan config:cache

echo "[3/8] Building route cache..."
php artisan route:cache

echo "[4/8] Building view cache..."
php artisan view:cache

echo "[5/8] Building event cache..."
php artisan event:cache

# Step 3: Clear opcache (old bytecode)
# optimize:clear removes config/route/view caches but they were just rebuilt above.
# The net effect is clearing opcache and any stale compiled files.
echo "[6/8] Clearing opcache and stale compiled files..."
php artisan optimize:clear

# Immediately rebuild caches that optimize:clear removed
php artisan config:cache
php artisan route:cache

# Step 4: Restart queue workers
# queue:restart signals workers to exit AFTER their current job finishes.
# This is already graceful — in-progress jobs complete before the worker exits.
# The supervisor/systemd will restart the worker process with the new code.
echo "[7/8] Restarting queue workers (graceful)..."
php artisan queue:restart

# Step 5: Verify production config
echo "[8/8] Verifying production config..."
APP_DEBUG=$(php artisan tinker --execute="echo config('app.debug') ? 'true' : 'false';" 2>/dev/null | tail -1)
if [ "$APP_DEBUG" = "true" ]; then
    echo "WARNING: APP_DEBUG is true! Set APP_DEBUG=false in production."
    exit 1
fi

# Check Sentry DSN is configured
if [ -z "${SENTRY_LARAVEL_DSN}" ]; then
    echo "WARNING: SENTRY_LARAVEL_DSN is not set — production errors will not be monitored"
fi

echo ""
echo "=== Post-Deploy Complete ==="
echo ""
echo "Note: For true zero-downtime deployment:"
echo "  - Use a load balancer with health check draining"
echo "  - Deploy to a new instance, verify health, then switch traffic"
echo "  - queue:restart is already graceful (finishes current job)"
echo ""
echo "Run smoke test to verify: ./scripts/smoke-test.sh \$APP_URL"
