#!/bin/bash
# Stop the Workout Planner server
# Usage: ./scripts/stop.sh

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
PID_FILE="$PROJECT_DIR/.server.pid"

if [ -f "$PID_FILE" ]; then
  PID=$(cat "$PID_FILE")
  if kill -0 "$PID" 2>/dev/null; then
    echo "Stopping server (PID $PID)..."
    kill "$PID"
    rm -f "$PID_FILE"
    echo "Server stopped."
  else
    echo "Server not running (stale PID file)."
    rm -f "$PID_FILE"
  fi
else
  echo "No PID file found. Server may not be running."
  # Try to find and kill any next server on port 3000
  PIDS=$(lsof -ti:3000 2>/dev/null)
  if [ -n "$PIDS" ]; then
    echo "Found process(es) on port 3000: $PIDS"
    echo "Kill them? (y/n)"
    read -r REPLY
    if [ "$REPLY" = "y" ]; then
      echo "$PIDS" | xargs kill
      echo "Killed."
    fi
  fi
fi
