#!/usr/bin/env bash
set -euo pipefail

echo "[migrate] waiting for postgres at $DATABASE_URL ..."
for i in {1..60}; do
  if node -e "
    import('pg').then(({ default: pg }) => {
      const c = new pg.Client({ connectionString: process.env.DATABASE_URL });
      c.connect().then(() => c.end()).then(() => process.exit(0)).catch(() => process.exit(1));
    });
  " 2>/dev/null; then
    echo "[migrate] postgres is ready."
    break
  fi
  sleep 1
done

echo "[migrate] pushing schema with drizzle-kit ..."
cd /app
pnpm --filter @workspace/db run push-force

echo "[migrate] seeding database ..."
pnpm --filter @workspace/scripts run seed || {
  echo "[migrate] seed reported a non-zero exit (often safe if data already exists). Continuing."
}

echo "[migrate] done."
