#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BACKEND_DIR="$ROOT_DIR/lotterLaravel"
API_URL="http://127.0.0.1:8000"
VITE_URL="http://localhost:5173"
REVERB_URL="ws://127.0.0.1:8080"
BACKEND_PORTS=(8000 8080 5173 5174)

# 只清理后端相关端口，避免影响手动启动的两个前端
stop_backend_listeners() {
  local signal=$1
  for port in "${BACKEND_PORTS[@]}"; do
    local pids
    pids=$(lsof -nP -iTCP:"$port" -sTCP:LISTEN -t 2>/dev/null || true)
    if [[ -n "$pids" ]]; then
      echo "Stopping backend port $port (PIDs: $pids)"
      # shellcheck disable=SC2086
      kill $signal $pids 2>/dev/null || true
    fi
  done
}

stop_backend_listeners TERM
sleep 1
stop_backend_listeners -9

pids=()
cleanup() {
  trap - INT TERM EXIT
  if ((${#pids[@]})); then
    kill "${pids[@]}" 2>/dev/null || true
  fi
}
trap cleanup INT TERM EXIT

echo "Starting backend local stack..."
echo "  - Laravel API : $API_URL"
echo "  - Vite assets : $VITE_URL"
echo "  - Reverb WS   : $REVERB_URL"
echo

echo "Starting backend (Laravel + queue + reverb + schedule + vite) …"
(
  cd "$BACKEND_DIR"
  composer run dev:realtime
) &
pids+=("$!")

echo
echo "Backend services are launching. Press Ctrl+C to stop them."
echo

# wait -n needs Bash 4.3+; macOS /bin/bash is 3.2
wait "${pids[@]}"
exit_code=$?
cleanup
exit "$exit_code"
