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

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

start_dev() {
  echo "==> Starting backend (Gin)..."
  (cd "${ROOT_DIR}/sproutgate-backend" && go run .) &
  BACKEND_PID=$!

  trap 'echo; echo "==> Stopping backend..."; kill ${BACKEND_PID} 2>/dev/null || true; exit 0' INT TERM

  echo "==> Starting frontend (React)..."
  cd "${ROOT_DIR}/sproutgate-frontend"
  if [ ! -d node_modules ]; then
    npm install
  fi
  npm run dev

  echo "==> Frontend stopped, shutting down backend..."
  kill ${BACKEND_PID} 2>/dev/null || true
}

build_frontend() {
  echo "==> Building frontend..."
  cd "${ROOT_DIR}/sproutgate-frontend"
  if [ ! -d node_modules ]; then
    npm install
  fi
  npm run build
}

case "${MODE}" in
  dev)
    start_dev
    ;;
  build)
    build_frontend
    ;;
  *)
    echo "Usage: ./sproutgate.sh [dev|build]"
    exit 1
    ;;
esac
