#!/usr/bin/env bash
# Run all three BeebBeeb web apps together: website (3000), superadmin (3001), investor (3002).
# They are wired to the LAN IP so they work from both this machine and a phone on the same WiFi.
#
#   ./run-webs.sh          # dev mode (hot reload) -- default
#   ./run-webs.sh build    # production build + start (next build && next start)
#   HOST_IP=1.2.3.4 ./run-webs.sh   # override the auto-detected LAN IP
#
# Ctrl+C stops all three.
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MODE="${1:-dev}"

# --- Node 20 (the machine default is v14, too old for Next) ---
NODE_BIN="$HOME/.nvm/versions/node/v20.20.0/bin"
[ -d "$NODE_BIN" ] && export PATH="$NODE_BIN:$PATH"
echo "node $(node -v)"

# --- LAN IP so the phone can reach the dashboards ---
HOST_IP="${HOST_IP:-$(hostname -I | awk '{print $1}')}"
echo "LAN IP: $HOST_IP"

# Backend base URLs (Docker stack ports)
ADMIN_API="http://$HOST_IP:8089"      # admin-gateway
INVESTOR_API="http://$HOST_IP:8090"   # investor-service

LOGDIR="$ROOT/.web-logs"
mkdir -p "$LOGDIR"

PIDS=()
cleanup() {
  echo ""
  echo "stopping web apps..."
  for pid in "${PIDS[@]}"; do kill "$pid" 2>/dev/null || true; done
  # next spawns children; sweep the ports too
  for p in 3000 3001 3002; do
    fuser -k "${p}/tcp" 2>/dev/null || true
  done
  wait 2>/dev/null || true
  echo "done."
}
trap cleanup INT TERM EXIT

# start <dir> <port> <label> <env assignments...>
start() {
  local dir="$1" port="$2" label="$3"; shift 3
  echo "starting $label on :$port  (log: $LOGDIR/$label.log)"
  if [ "$MODE" = "build" ]; then
    ( cd "$ROOT/$dir" && env "$@" npx next build && env "$@" npx next start -H 0.0.0.0 -p "$port" ) \
      >"$LOGDIR/$label.log" 2>&1 &
  else
    ( cd "$ROOT/$dir" && env "$@" npx next dev -H 0.0.0.0 -p "$port" ) \
      >"$LOGDIR/$label.log" 2>&1 &
  fi
  PIDS+=("$!")
}

start website    3000 website    "NEXT_PUBLIC_INVESTOR_URL=http://$HOST_IP:3002"
start superadmin 3001 superadmin "NEXT_PUBLIC_ADMIN_API_URL=$ADMIN_API"
start investor   3002 investor   "NEXT_PUBLIC_INVESTOR_API_URL=$INVESTOR_API"

echo ""
echo "waiting for the apps to come up (mode: $MODE)..."
for i in $(seq 1 60); do
  up=0
  for p in 3000 3001 3002; do
    [ "$(curl -s --max-time 2 -o /dev/null -w '%{http_code}' "localhost:$p" 2>/dev/null)" = "200" ] && up=$((up+1))
  done
  [ "$up" = 3 ] && break
  sleep 3
done

cat <<EOF

============================================================
  BeebBeeb web apps are running
------------------------------------------------------------
  Website      http://localhost:3000   |  http://$HOST_IP:3000
  Super Admin  http://localhost:3001   |  http://$HOST_IP:3001
  Investor     http://localhost:3002   |  http://$HOST_IP:3002
------------------------------------------------------------
  Backend expected at $ADMIN_API (admin-gateway) / :8090 (investor)
  Logs: $LOGDIR/{website,superadmin,investor}.log
  Press Ctrl+C to stop all three.
============================================================
EOF

# Keep the script alive so Ctrl+C triggers cleanup and the servers stay attached.
wait
