#!/usr/bin/env bash
# Runs central + tenant migrations for the Kedebah Commerce stack.
#
# The stack points at a PRE-EXISTING database, so migrations are OFF by default
# in the entrypoint. Run this ONLY when you intentionally want to migrate.
#
# Usage:
#   bin/migrate.sh              # central migrations for every service
#   bin/migrate.sh tenants      # also run tenants:migrate where supported
set -euo pipefail
cd "$(dirname "$0")/.."

MODE="${1:-central}"

run() { # <service> <artisan args...>
  local svc="$1"; shift
  echo "==> [$svc] php artisan $*"
  docker compose run --rm --no-deps "$svc" php artisan "$@" || \
    echo "    (skipped/failed for $svc)"
}

echo "### Central migrations"
for svc in auth onboarding email tenant-processor finance commerce; do
  run "$svc" migrate --force
done

if [ "$MODE" = "tenants" ]; then
  echo "### Tenant migrations"
  # tenant-processor owns tenant provisioning/migrations (incl. finance/ path)
  run tenant-processor tenants:migrate --force
  run tenant-processor tenants:migrate --path=database/migrations/finance --force
  run finance tenants:migrate --force
fi

echo "### Done."
