#!/usr/bin/env bash
#
# Production deploy script for the Manabou backend.
#
# The detective feature (and others) ship DB migrations alongside code. If code
# is deployed without running its migrations, the app writes to columns that
# don't exist yet and fails at runtime — e.g. `POST /detective/board/generate`
# returned a 422 because the `add_detective_depth_columns` migration hadn't run.
# This script guards against that: it refuses to finish a deploy while there are
# pending migrations, and applies them as a normal deploy step.
#
# Usage:
#   ./deploy.sh            # full deploy (pull deps, migrate, cache, restart)
#   ./deploy.sh --check    # CI/pre-deploy guard: exit non-zero if migrations pend
#
# Adapt the PHP binary / queue restart to your host (Forge, cPanel, VPS, etc.).

set -euo pipefail

PHP="${PHP_BIN:-php}"
ARTISAN="$PHP artisan"

cd "$(dirname "$0")"

# ── Pending-migration guard ──────────────────────────────────────────────────
# `migrate:status` lists every migration with Ran? = Yes/No (or [N] Pending).
# We treat any "Pending"/"No" row as pending work.
pending_migrations() {
  $ARTISAN migrate:status 2>/dev/null | grep -Eiq "pending|\bNo\b"
}

echo "▶ Current migration status:"
$ARTISAN migrate:status || true
echo

# --check mode: used as a CI/pre-deploy gate. Fail if anything is unmigrated.
if [[ "${1:-}" == "--check" ]]; then
  if pending_migrations; then
    echo "✖ Pending migrations detected — deploy would leave the schema out of date."
    echo "  Run ./deploy.sh (without --check) to apply them."
    exit 1
  fi
  echo "✔ No pending migrations."
  exit 0
fi

# ── Full deploy ──────────────────────────────────────────────────────────────
echo "▶ Installing dependencies…"
composer install --no-dev --optimize-autoloader --no-interaction

echo "▶ Running migrations…"
$ARTISAN migrate --force

# Fail loudly if anything is still pending after migrating (e.g. a migration
# errored or was skipped) — better a failed deploy than silent schema drift.
if pending_migrations; then
  echo "✖ Migrations still pending after 'migrate --force'. Aborting."
  exit 1
fi

echo "▶ Caching config/routes/views…"
$ARTISAN config:cache
$ARTISAN route:cache
$ARTISAN view:cache

echo "▶ Restarting queue workers…"
$ARTISAN queue:restart

echo "✔ Deploy complete — schema is up to date."
