#!/usr/bin/env bash
set -euo pipefail
mode="${1:-app}"

case "$mode" in
  app)
    echo "[entrypoint] running drizzle migrations..."
    npx tsx --tsconfig tsconfig.json src/lib/db/migrate.ts || {
      echo "[entrypoint] WARN: migrate failed (possibly already applied); continuing"
    }
    echo "[entrypoint] seeding demo workspace if DB empty..."
    npx tsx --tsconfig tsconfig.json scripts/seed-dev.ts || {
      echo "[entrypoint] WARN: seed-dev failed; continuing"
    }
    echo "[entrypoint] seeding section templates (idempotent)..."
    npx tsx --tsconfig tsconfig.json scripts/seed-section-templates.ts || {
      echo "[entrypoint] WARN: seed failed; continuing"
    }
    echo "[entrypoint] starting next.js on :3000 (bind 0.0.0.0)..."
    exec ./node_modules/.bin/next start -H 0.0.0.0 -p 3000
    ;;
  worker)
    echo "[entrypoint] starting send-worker..."
    exec npx tsx --tsconfig tsconfig.json src/worker/index.ts
    ;;
  *)
    exec "$@"
    ;;
esac
