#!/bin/sh
set -eu

cd /app

node scripts/resolve-database-url.mjs

echo "[entrypoint] waiting for database…"
node scripts/wait-for-db.mjs

if [ "${RUN_DB_MIGRATE:-true}" = "true" ]; then
  echo "[entrypoint] running migrations…"
  node scripts/migrate.mjs
fi

if [ "${SEED_ON_BOOT:-false}" = "true" ]; then
  echo "[entrypoint] seeding (optional)…"
  if command -v npx >/dev/null 2>&1 && [ -f scripts/seed.ts ]; then
    npx --yes tsx --env-file=/dev/null scripts/seed.ts \
      || echo "[entrypoint] seed skipped/failed (non-fatal)"
  else
    echo "[entrypoint] seed tooling not available — skip"
  fi
fi

export HOSTNAME="${HOSTNAME:-0.0.0.0}"
export PORT="${PORT:-3000}"

echo "[entrypoint] starting Next.js on ${HOSTNAME}:${PORT}"
exec npx next start --hostname "$HOSTNAME" --port "$PORT"
