#!/usr/bin/env bash
# nvm + Node from the repo's .nvmrc + corepack + pnpm at the version pinned
# in package.json's packageManager field.
set -euo pipefail
# shellcheck source=./lib.sh
source "$(cd "$(dirname "$0")" && pwd)/lib.sh"
require_debian
require_not_root

NVM_VERSION="v0.40.1"
NVM_DIR="$HOME/.nvm"

if [[ -d "$NVM_DIR" ]]; then
  skip "nvm already installed at $NVM_DIR."
else
  log "Installing nvm $NVM_VERSION."
  curl -fsSL "https://raw.githubusercontent.com/nvm-sh/nvm/$NVM_VERSION/install.sh" | bash
  ok "nvm installed."
fi

# Source nvm so we can use it in this shell.
export NVM_DIR
# shellcheck disable=SC1091
source "$NVM_DIR/nvm.sh"

# Read .nvmrc from the repo root.
REPO_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || true)"
if [[ -z "$REPO_ROOT" ]]; then
  err "Run from inside a git checkout of apf_portal (no repo root found)."
  exit 1
fi
if [[ ! -f "$REPO_ROOT/.nvmrc" ]]; then
  warn "$REPO_ROOT/.nvmrc not found — installing Node LTS as fallback."
  nvm install --lts
  nvm alias default 'lts/*'
else
  NODE_VER="$(<"$REPO_ROOT/.nvmrc")"
  log "Installing Node $NODE_VER (from $REPO_ROOT/.nvmrc)."
  nvm install "$NODE_VER"
  nvm alias default "$NODE_VER"
  ok "Node $(node --version) active."
fi

# corepack — provides pnpm + yarn shims, reads packageManager from package.json.
corepack enable
ok "corepack enabled."

# Warm pnpm to download the pinned version.
if [[ -f "$REPO_ROOT/package.json" ]]; then
  pushd "$REPO_ROOT" >/dev/null
  pnpm --version >/dev/null
  ok "pnpm $(pnpm --version) ready (from package.json packageManager)."
  popd >/dev/null
fi

log "Reload your shell (exec zsh -l) so nvm + node + pnpm are on PATH."
