#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."

echo "Stopping Nexus..."

# 1. Stop any legacy local dev server
if [ -f /tmp/nexus-dev.pid ]; then
  PID=$(cat /tmp/nexus-dev.pid)
  if kill -0 "$PID" 2>/dev/null; then
    echo "  Stopping Next.js (PID $PID)..."
    kill "$PID" 2>/dev/null || true
    sleep 1
    kill -9 "$PID" 2>/dev/null || true
  fi
  rm -f /tmp/nexus-dev.pid
fi

# Also kill anything on port 3100 (cross-platform: lsof works on Linux + macOS)
if command -v lsof >/dev/null 2>&1; then
  lsof -ti:3100 2>/dev/null | xargs kill 2>/dev/null || true
elif command -v fuser >/dev/null 2>&1; then
  fuser -k 3100/tcp 2>/dev/null || true
fi

# 2. Stop Docker services (keep data volumes)
echo "  Stopping app, PostgreSQL and Redis..."
docker compose --profile full stop app postgres redis 2>/dev/null || true

echo ""
echo "Nexus stopped."
