#!/bin/sh
set -e

# Keep DATABASE_URL consistent for every Prisma command
export DATABASE_URL="${DATABASE_URL:-postgresql://innungsapp:innungsapp@postgres:5432/innungsapp?schema=public}"
MIGRATIONS_DIR="./packages/shared/prisma/migrations"

# Debug: Check environment variables
echo "========================================"
echo "Environment Variables Check:"
echo "========================================"
echo "DATABASE_URL: $DATABASE_URL"
echo "BETTER_AUTH_URL: ${BETTER_AUTH_URL:-[not set]}"
echo "BETTER_AUTH_BASE_URL: ${BETTER_AUTH_BASE_URL:-[not set]}"
if [ -n "$BETTER_AUTH_SECRET" ]; then
  echo "BETTER_AUTH_SECRET: [set]"
else
  echo "BETTER_AUTH_SECRET: [not set]"
fi
echo "NEXT_PUBLIC_APP_URL: ${NEXT_PUBLIC_APP_URL:-[not set]}"
echo "NODE_ENV: ${NODE_ENV:-[not set]}"
echo "========================================"
echo ""

run_with_retries() {
  attempt=1
  max_attempts=20

  while [ "$attempt" -le "$max_attempts" ]; do
    if "$@"; then
      return 0
    fi

    if [ "$attempt" -eq "$max_attempts" ]; then
      echo "Command failed after ${max_attempts} attempts."
      return 1
    fi

    echo "Database not ready yet. Retry ${attempt}/${max_attempts} in 3s..."
    attempt=$((attempt + 1))
    sleep 3
  done
}

# Prefer migration-based deploys. Fall back to db push when no migrations exist yet.
# set -- "$MIGRATIONS_DIR"/*/migration.sql
# if [ -f "$1" ]; then
#   echo "Applying Prisma migrations..."
#   run_with_retries npx prisma migrate deploy --schema=./packages/shared/prisma/schema.prisma
# else
#   echo "No Prisma migrations found. Syncing schema with db push..."
#   run_with_retries npx prisma db push --skip-generate --schema=./packages/shared/prisma/schema.prisma
# fi

echo "Starting Next.js server..."
exec node apps/admin/server.js
