#!/bin/sh
set -eu

STATE_DIR="/state"
MARKER_FILE="$STATE_DIR/dev-bootstrap-complete"

mkdir -p "$STATE_DIR"

EXPECTED_TURBO_VERSION="$(node -e "const lock=require('/app/package-lock.json'); process.stdout.write(lock.packages?.['node_modules/turbo']?.version || '')")"
INSTALLED_TURBO_VERSION="$(node -e "try { process.stdout.write(require('/app/node_modules/turbo/package.json').version || '') } catch (_) {}")"

if [ -n "$EXPECTED_TURBO_VERSION" ] && [ "$INSTALLED_TURBO_VERSION" != "$EXPECTED_TURBO_VERSION" ]; then
  echo "[migrate] Refreshing node_modules volume for turbo $EXPECTED_TURBO_VERSION"
  npm ci --no-fund --no-audit
fi

echo "[migrate] Generating database client"
npm run db:generate

STORAGE_ROOT="${FILE_STORAGE_ROOT:-}"
LEGACY_STORAGE_ROOT="${LEGACY_STORAGE_ROOT:-/app/apps/api/src/lib/storage}"

if [ -n "$STORAGE_ROOT" ]; then
  mkdir -p "$STORAGE_ROOT"
  if [ -d "$LEGACY_STORAGE_ROOT" ]; then
    echo "[migrate] Syncing legacy uploads into the dev storage volume"
    cp -Rn "$LEGACY_STORAGE_ROOT"/. "$STORAGE_ROOT"/ 2>/dev/null || true
  fi
fi

echo "[migrate] Applying pending migrations"
npm run db:deploy

if [ -f "$MARKER_FILE" ]; then
  echo "[migrate] Existing dev database detected; skipping seed"
  exit 0
fi

echo "[migrate] First dev bootstrap; seeding data"
npm run db:seed

touch "$MARKER_FILE"
echo "[migrate] Dev bootstrap complete"
