#!/usr/bin/env bash
#
# Start the development servers (API + web).
# Runs both in parallel and shuts both down on Ctrl-C.
#
set -euo pipefail

cd "$(dirname "$0")"

WEB_PORT=4500
API_PORT=4501

api_pid=""
web_pid=""

# Free a port by killing whatever is listening on it (stale dev servers).
free_port() {
  local port="$1"
  local pids
  pids="$(lsof -tiTCP:"$port" -sTCP:LISTEN 2>/dev/null || true)"
  if [ -n "$pids" ]; then
    echo "Freeing port $port (killing: $pids)"
    kill $pids 2>/dev/null || true
    sleep 1
  fi
}

# Kill the child servers once, on Ctrl-C or exit.
cleanup() {
  trap - EXIT INT TERM
  echo ""
  echo "Shutting down dev servers..."
  [ -n "$api_pid" ] && kill "$api_pid" 2>/dev/null || true
  [ -n "$web_pid" ] && kill "$web_pid" 2>/dev/null || true
}
trap cleanup EXIT INT TERM

free_port "$API_PORT"
free_port "$WEB_PORT"

echo "Starting API  -> http://localhost:$API_PORT"
pnpm --filter @jorgecuadros/api start:dev &
api_pid=$!

echo "Starting web  -> http://localhost:$WEB_PORT"
pnpm --filter @jorgecuadros/web dev &
web_pid=$!

# Wait for both. Ctrl-C fires the trap, which kills them.
wait
