#!/usr/bin/env bash
#
# Deploys one setup (test or live) on the VPS.
#
#   bash deploy.sh test
#   bash deploy.sh live
#
# What it does:
#   1. API:   git pull, npm ci, Prisma migrations, build
#   2. Admin: git pull, npm ci, build (Nginx serves the built files)
#   3. Restarts the API and the nightly worker with PM2 and checks that the API answers
#
# See docs/server-setup.md for the one-time server setup this script expects.

set -euo pipefail

# Everything is inside main() so that "git pull" updating this file
# cannot change the script while it is still running.
main() {
  local env_name="${1:-}"

  if [[ "$env_name" != "test" && "$env_name" != "live" ]]; then
    echo "Usage: bash deploy.sh test|live"
    exit 1
  fi

  local base_dir="${BASE_DIR:-/var/www/easy-paper-trading}"
  local api_dir="$base_dir/$env_name/api"
  local admin_dir="$base_dir/$env_name/admin"
  local pm2_name="ept-api-$env_name"
  local worker_name="ept-worker-$env_name"

  if [[ ! -f "$api_dir/.env" ]]; then
    echo "Missing $api_dir/.env - create it first (see docs/server-setup.md)."
    exit 1
  fi

  echo "==> [$env_name] API: pulling latest code"
  cd "$api_dir"
  git pull --ff-only

  echo "==> [$env_name] API: installing packages"
  npm ci

  echo "==> [$env_name] API: applying database migrations"
  npx prisma generate
  npx prisma migrate deploy

  echo "==> [$env_name] API: building"
  npm run build

  if [[ -f "$admin_dir/package.json" ]]; then
    echo "==> [$env_name] Admin: pulling latest code"
    cd "$admin_dir"
    git pull --ff-only

    echo "==> [$env_name] Admin: installing packages"
    npm ci

    echo "==> [$env_name] Admin: building"
    npm run build
  else
    echo "==> [$env_name] Admin: no project found in $admin_dir, skipping"
  fi

  echo "==> [$env_name] API: restarting with PM2"
  cd "$api_dir"
  if pm2 describe "$pm2_name" > /dev/null 2>&1; then
    pm2 restart "$pm2_name" --update-env
  else
    pm2 start dist/server.js --name "$pm2_name" --cwd "$api_dir"
  fi

  # The nightly worker (stock prices) runs as its own process, next to the API
  echo "==> [$env_name] Worker: restarting with PM2"
  if pm2 describe "$worker_name" > /dev/null 2>&1; then
    pm2 restart "$worker_name" --update-env
  else
    pm2 start dist/worker.js --name "$worker_name" --cwd "$api_dir"
  fi
  pm2 save

  # Read PORT from .env so we check the right setup
  local port
  port="$(grep -E '^PORT=' "$api_dir/.env" | tail -n 1 | cut -d= -f2 | tr -d '"'"'"' \r')"
  port="${port:-4000}"

  echo "==> [$env_name] API: checking http://127.0.0.1:$port/api/health"
  local attempt
  for attempt in 1 2 3 4 5 6 7 8 9 10; do
    if curl -fsS "http://127.0.0.1:$port/api/health" > /dev/null 2>&1; then
      echo "==> [$env_name] Deploy finished. API is up on port $port."
      exit 0
    fi
    sleep 1
  done

  echo "==> [$env_name] API did not answer on port $port. Check: pm2 logs $pm2_name"
  exit 1
}

main "$@"
