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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
LOG_DIR="$ROOT_DIR/.tmp/backend-logs"
DATABASE_URL="${DATABASE_URL:-postgres://fable:fable_dev_password@127.0.0.1:5432/fable?sslmode=disable}"
TOKEN_SECRET="${TOKEN_SECRET:-local-dev-secret-change-me}"
TOKEN_TTL="${TOKEN_TTL:-24h}"
mkdir -p "$LOG_DIR"

pids=()

cleanup() {
  for pid in "${pids[@]:-}"; do
    if kill -0 "$pid" >/dev/null 2>&1; then
      kill "$pid" >/dev/null 2>&1 || true
    fi
  done
}

trap cleanup EXIT INT TERM

start_service() {
  local name="$1"
  local port="$2"
  echo "Starting $name service on :$port"
  (cd "$ROOT_DIR/services" && PORT="$port" DATABASE_URL="$DATABASE_URL" TOKEN_SECRET="$TOKEN_SECRET" TOKEN_TTL="$TOKEN_TTL" go run "./cmd/$name") >"$LOG_DIR/$name.log" 2>&1 &
  pids+=("$!")
}

start_service auth 8081
start_service user 8082
start_service content 8083
start_service taxonomy 8084
start_service speaker 8085
start_service subscription 8086
start_service notification 8087
start_service comment 8088
start_service search 8089
start_service analytics 8090
start_service audit 8091
start_service media 8092

echo "Building Node gateway"
npm --workspace @fable/gateway run build

echo "Starting Node gateway on :3000"
AUTH_SERVICE_URL=http://127.0.0.1:8081 \
USER_SERVICE_URL=http://127.0.0.1:8082 \
CONTENT_SERVICE_URL=http://127.0.0.1:8083 \
TAXONOMY_SERVICE_URL=http://127.0.0.1:8084 \
SPEAKER_SERVICE_URL=http://127.0.0.1:8085 \
SUBSCRIPTION_SERVICE_URL=http://127.0.0.1:8086 \
NOTIFICATION_SERVICE_URL=http://127.0.0.1:8087 \
COMMENT_SERVICE_URL=http://127.0.0.1:8088 \
SEARCH_SERVICE_URL=http://127.0.0.1:8089 \
ANALYTICS_SERVICE_URL=http://127.0.0.1:8090 \
AUDIT_SERVICE_URL=http://127.0.0.1:8091 \
MEDIA_SERVICE_URL=http://127.0.0.1:8092 \
GATEWAY_PORT=3000 \
node "$ROOT_DIR/apps/gateway/dist/index.js" &
pids+=("$!")

echo "Backend is running. Logs: $LOG_DIR"
echo "Gateway health: http://localhost:3000/health"
echo "Press Ctrl+C to stop."

wait
