#!/usr/bin/env bash
#
# split-migrations.sh — partition the migration set for multi-tenancy.
#
# Run ONCE from the Laravel project root (…/go.nelarahealth.com), AFTER you have
# committed/backed up the current tree. It is safe to re-run (idempotent).
#
#   bash scripts/split-migrations.sh
#
# Result:
#   database/migrations/                 -> emptied of HMIS migrations (top level)
#   database/migrations/central/         -> 6 platform tables (already shipped)
#   database/migrations/tenant/          -> the HMIS schema, run via `tenants:migrate`
#   database/migrations/_quarantined/    -> real-data / prod-reset migrations,
#                                           NEVER run for a new tenant. Kept only
#                                           as reference for CRH onboarding.
#
# WHY a bare `php artisan migrate` is now a no-op: every HMIS migration moves
# into tenant/, and the central ones live in central/. Neither is in the default
# top-level path, so nothing runs unintentionally against the wrong database.
#
set -euo pipefail

MIG="database/migrations"

if [ ! -d "$MIG" ]; then
  echo "ERROR: run this from the Laravel project root (no $MIG found)." >&2
  exit 1
fi

mkdir -p "$MIG/tenant" "$MIG/_quarantined"

# Migrations that must NEVER run when building a new tenant database:
#   500001  wipe_demo_data        -> production reset; truncates + creates a
#                                    CRH-specific admin. Pointless and wrong for
#                                    a fresh tenant.
#   500002  import_clean_patients -> imports 5,308 REAL patients (PII).
#   500003  import_services_pricelist -> imports the real 595-item price list;
#                                    replaced by a synthetic catalogue in the
#                                    demo seeder.
QUARANTINE=(
  "2026_04_11_500001_wipe_demo_data.php"
  "2026_04_11_500002_import_clean_patients.php"
  "2026_04_11_500003_import_services_pricelist.php"
)

is_quarantined() {
  local name="$1"
  for q in "${QUARANTINE[@]}"; do
    [ "$name" = "$q" ] && return 0
  done
  return 1
}

moved=0; quarantined=0
# Only top-level *.php files (skip the central/, tenant/, _quarantined/ subdirs).
for f in "$MIG"/*.php; do
  [ -e "$f" ] || continue
  base="$(basename "$f")"
  if is_quarantined "$base"; then
    git mv "$f" "$MIG/_quarantined/$base" 2>/dev/null || mv "$f" "$MIG/_quarantined/$base"
    echo "  quarantined  $base"
    quarantined=$((quarantined+1))
  else
    git mv "$f" "$MIG/tenant/$base" 2>/dev/null || mv "$f" "$MIG/tenant/$base"
    moved=$((moved+1))
  fi
done

echo ""
echo "Done. $moved migration(s) -> tenant/ ; $quarantined -> _quarantined/."
echo "Central migrations remain in $MIG/central/ (run separately against nelara_master)."
echo ""
echo "Sanity check — top level should now contain only the subdirectories:"
ls -1 "$MIG"
