#!/usr/bin/env bash
# verify-pb-migration.sh — Check whether a PocketBase migration roadmap item
# is actually live in the running container.
#
# Usage:
#   ./verify-pb-migration.sh <migration-filename>
#   ./verify-pb-migration.sh 1740000000020_users_create_role_guard.js
#
# Exits 0 only when ALL three checks pass:
#   1. The file exists in the repo's pb_migrations/ directory.
#   2. The file has been copied into the container at /pb_data/migrations/.
#   3. `pocketbase migrate up` reports "No new migrations to apply."
#      (meaning the migration is already applied — not pending)
#
# Context: roadmap_5.2.md items often have a status of ❌ NOT DONE that lags
# behind reality. Before planning a PB-migration item, run this to confirm it
# is genuinely unstarted vs. already shipped but un-memoed.

set -euo pipefail

if [ $# -lt 1 ]; then
  echo "Usage: $0 <migration-filename>" >&2
  exit 2
fi

MIGRATION_FILE="$1"
REPO_PB_DIR="$(cd "$(dirname "$0")/../../pb_migrations" 2>/dev/null && pwd || echo pb_migrations)"

# Locate the pocketbase container.
PB_CID=$(docker ps --format '{{.ID}} {{.Names}}' | awk '$2=="pocketbase"{print $1; exit}')
if [ -z "$PB_CID" ]; then
  echo "FAIL: no 'pocketbase' container running." >&2
  exit 1
fi

STATUS=0

# 1. File exists in repo.
if [ -f "$REPO_PB_DIR/$MIGRATION_FILE" ]; then
  echo "OK  (repo)   : $REPO_PB_DIR/$MIGRATION_FILE exists"
else
  echo "MISS(repo)   : $REPO_PB_DIR/$MIGRATION_FILE not found"
  STATUS=1
fi

# 2. File exists inside the container.
if docker exec "$PB_CID" test -f "/pb_data/migrations/$MIGRATION_FILE" 2>/dev/null; then
  echo "OK  (container): /pb_data/migrations/$MIGRATION_FILE present"
else
  echo "MISS(container): /pb_data/migrations/$MIGRATION_FILE not copied into $PB_CID"
  STATUS=1
fi

# 3. migrate up is a no-op (migration already applied).
MIGRATE_OUT=$(docker exec "$PB_CID" /usr/local/bin/pocketbase migrate up --dir=/pb_data --migrationsDir=/pb_data/migrations 2>&1 || true)
if echo "$MIGRATE_OUT" | grep -q "No new migrations to apply"; then
  echo "OK  (applied) : migrate up reports \"No new migrations to apply.\""
else
  echo "PENDING       : migrate up output: $MIGRATE_OUT"
  STATUS=1
fi

exit $STATUS