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

ORIG_CMD=("$@")

if [[ "${SKIP_DB_INIT:-}" == "1" ]]; then
  echo "[entrypoint] SKIP_DB_INIT=1, skipping database initialization." >&2
  exec "${ORIG_CMD[@]}"
fi

# 若未显式提供 DATABASE_URL，则给出一个提示性默认
: ${DATABASE_URL:=postgresql://auth_user:auth_pass@db:5432/auth_db}
export DATABASE_URL

# 等待数据库可连接（最多 60 次，每次 1s）
echo "[entrypoint] waiting for database: $DATABASE_URL"
TRIES=0
until uv run python - <<'PY' 2>/dev/null; do
import sys, os
from urllib.parse import urlparse

url = os.environ.get("DATABASE_URL", "")
parsed = urlparse(url)
host = parsed.hostname or "db"
port = parsed.port or 5432
user = parsed.username or "postgres"
password = parsed.password or ""
db = parsed.path.lstrip("/") or "postgres"

try:
    import psycopg2
    conn = psycopg2.connect(user=user, password=password, host=host, port=port, database=db, connect_timeout=3)
    conn.close()
    sys.exit(0)
except:
    sys.exit(1)
PY
  TRIES=$((TRIES+1))
  if [ "$TRIES" -ge 60 ]; then
    echo "[entrypoint] database not ready after ${TRIES}s, continue anyway"
    break
  fi
  sleep 1
done

# 初始化/升级数据库（Prisma db push）
echo "[entrypoint] init/upgrade database via 'prisma db push'"
PRISMA_CMD=(uv run prisma db push --skip-generate)
if [[ "${PRISMA_ACCEPT_DATA_LOSS:-}" == "1" ]]; then
  PRISMA_CMD+=(--accept-data-loss)
fi

"${PRISMA_CMD[@]}" || echo "[entrypoint] prisma db push failed, continuing anyway"

exec "${ORIG_CMD[@]}"
