#!/usr/bin/env bash

set -euo pipefail

# This script runs database migrations for all services that define a migrate script.
# Ensure databases are reachable and required env vars are set (e.g., DATABASE_URL or individual PG vars).

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

# Default services. If arguments are provided, they will override this list.
default_services=(
  "user-auth"
  "template-manager"
)

if [ "$#" -gt 0 ]; then
  services=("$@")
else
  services=("${default_services[@]}")
fi

echo "Running migrations for services in: ${ROOT_DIR}/services"
echo "Target services: ${services[*]}"

for service in "${services[@]}"; do
  SERVICE_DIR="${ROOT_DIR}/services/${service}"
  if [ ! -d "${SERVICE_DIR}" ]; then
    echo "Skipping ${service}: directory not found at ${SERVICE_DIR}" >&2
    continue
  fi

  if [ ! -f "${SERVICE_DIR}/package.json" ]; then
    echo "Skipping ${service}: package.json not found" >&2
    continue
  fi

  echo "\n========================================"
  echo "➡️  ${service}: installing deps (ci)"
  echo "========================================"
  (cd "${SERVICE_DIR}" && npm ci --no-audit --no-fund --prefer-offline)

  echo "\n========================================"
  echo "🚀 ${service}: running migrations"
  echo "========================================"

  # Attempt to run migrate; if not defined, npm will error and we handle gracefully
  if (cd "${SERVICE_DIR}" && npm run -s migrate); then
    echo "✅ ${service}: migrations completed"
  else
    echo "⚠️  ${service}: 'npm run migrate' failed or not defined; skipping"
  fi
done

echo "\n✅ All migrations attempted. Review logs above for any errors."


