#!/bin/sh

# Exit on error
set -e

# ========================================
# MIGRATION SCRIPT FOR ALL SERVICES
# ========================================

# Get root directory (one level above this script)
ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"

# Default services list (can be overridden by CLI args)
default_services="shared-schemas user-auth template-manager unified-tech-stack-service git-integration"

# If arguments are passed, they override default services
if [ "$#" -gt 0 ]; then
  services="$*"
else
  services="$default_services"
fi

# Log function with timestamp
log() {
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*"
}

log "Starting database migrations..."
log "Root directory: ${ROOT_DIR}"
log "Target services: ${services}"

# Validate required environment variables (if using DATABASE_URL or PG vars)
if [ -z "${DATABASE_URL:-}" ]; then
  log "ERROR: Missing required environment variable: DATABASE_URL"
  exit 1
fi

# Always attempt to run migrations on startup.
# Each service's migration script must be idempotent and skip already-applied versions.
# The previous global marker skip is removed to allow new migrations to apply automatically.

# Track failed services
failed_services=""

for service in $services; do
  SERVICE_DIR="${ROOT_DIR}/services/${service}"

  if [ ! -d "${SERVICE_DIR}" ]; then
    log "Skipping ${service}: directory not found at ${SERVICE_DIR}"
    continue
  fi

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

  log "========================================"
  log "➡️  ${service}: installing dependencies"
  log "========================================"

  # Check if package-lock.json exists, use appropriate install command
  if [ -f "${SERVICE_DIR}/package-lock.json" ]; then
    if ! (cd "${SERVICE_DIR}" && npm ci --no-audit --no-fund --prefer-offline); then
      log "ERROR: Failed to install dependencies for ${service}"
      failed_services="${failed_services} ${service}"
      continue
    fi
  else
    if ! (cd "${SERVICE_DIR}" && npm install --no-audit --no-fund); then
      log "ERROR: Failed to install dependencies for ${service}"
      failed_services="${failed_services} ${service}"
      continue
    fi
  fi

  log "========================================"
  log "🚀 ${service}: running migrations"
  log "========================================"

  if grep -q '"migrate":' "${SERVICE_DIR}/package.json"; then
    if (cd "${SERVICE_DIR}" && npm run -s migrate); then
      log "✅ ${service}: migrations completed successfully"
    else
      log "⚠️  ${service}: migration failed"
      failed_services="${failed_services} ${service}"
    fi
  else
    log "ℹ️  ${service}: no 'migrate' script found; skipping"
  fi
done

log "========================================"
if [ -n "$failed_services" ]; then
  log "MIGRATIONS COMPLETED WITH ERRORS"
  log "Failed services: $failed_services"
  exit 1
else
  log "✅ All migrations completed successfully"
fi
