#!/usr/bin/env bash

set -euo pipefail

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

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

# Default services list (can be overridden by CLI args)
default_services=(
  "user-auth"
  "template-manager"
)

# 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)
required_vars=("DATABASE_URL")
missing_vars=()

for var in "${required_vars[@]}"; do
  if [ -z "${!var:-}" ]; then
    missing_vars+=("$var")
  fi
done

if [ ${#missing_vars[@]} -gt 0 ]; then
  log "ERROR: Missing required environment variables: ${missing_vars[*]}"
  exit 1
fi

# Check if migrations have already been completed successfully
MIGRATION_MARKER="/tmp/migrations-completed"
if [ -f "${MIGRATION_MARKER}" ]; then
  log "✅ Migrations already completed successfully (marker file exists)"
  log "To force re-run migrations, delete: ${MIGRATION_MARKER}"
  exit 0
fi

# 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 "========================================"

  if ! (cd "${SERVICE_DIR}" && npm ci --no-audit --no-fund --prefer-offline); then
    log "ERROR: Failed to install dependencies for ${service}"
    failed_services+=("${service}")
    continue
  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+=("${service}")
    fi
  else
    log "ℹ️  ${service}: no 'migrate' script found; skipping"
  fi
done

log "========================================"
if [ ${#failed_services[@]} -gt 0 ]; then
  log "MIGRATIONS COMPLETED WITH ERRORS"
  log "Failed services: ${failed_services[*]}"
  exit 1
else
  log "✅ All migrations completed successfully"
  # Create marker file to indicate successful completion
  touch "${MIGRATION_MARKER}"
  log "📝 Created migration completion marker: ${MIGRATION_MARKER}"
fi
