#!/usr/bin/env bash
# Emergency Rollback Procedure
# Usage: ./scripts/rollback.sh [previous-release-tag]
#
# WARNING: This script handles cache/queue rollback only.
# Code rollback (git checkout, deploy tool revert) must be done separately.
# Irreversible migrations (data migrations, column drops) cannot be rolled back automatically.

set -euo pipefail

echo ""
echo "=== Emergency Rollback ==="
echo ""

PREVIOUS_RELEASE="${1:-}"

# Step 1: Code rollback guidance
if [ -n "$PREVIOUS_RELEASE" ]; then
    echo "Target release: $PREVIOUS_RELEASE"
    echo "Run your deploy tool to revert to this release, or:"
    echo "  git checkout $PREVIOUS_RELEASE"
    echo ""
else
    echo "No target release specified."
    echo "Usage: $0 <previous-release-tag>"
    echo "Proceeding with cache/queue reset only."
    echo ""
fi

# Step 2: Clear and rebuild caches
echo "Clearing caches..."
php artisan optimize:clear
echo "Rebuilding caches..."
php artisan config:cache
php artisan route:cache
php artisan view:cache
echo "Caches rebuilt."
echo ""

# Step 3: Restart queue workers (graceful — finishes current job)
echo "Restarting queue workers..."
php artisan queue:restart
echo "Queue restart signal sent (workers will exit after current job)."
echo ""

# Step 4: Migration rollback guidance
echo "=== Migration Rollback ==="
echo "If a migration was run in this deploy, check if rollback is safe:"
echo "  php artisan migrate:status"
echo ""
echo "Only rollback if the migration is reversible (has a proper down() method):"
echo "  php artisan migrate:rollback --step=1"
echo ""
echo "WARNING: Irreversible migrations (data migrations, column drops, data transforms)"
echo "cannot be rolled back automatically. These require manual database intervention."
echo ""

# Step 5: Verification
echo "=== Post-Rollback Verification ==="
echo "Run the smoke test to verify the app is healthy:"
echo "  ./scripts/smoke-test.sh \$APP_URL"
echo ""
echo "Check the health endpoint:"
echo "  curl -sf \$APP_URL/up"
echo ""

echo "Rollback complete. Monitor logs for errors."
