#!/bin/sh
set -eu

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

mkdir -p "$STATE_DIR"

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"
