#!/bin/sh
set -e

# Keep DATABASE_URL consistent for every Prisma command
export DATABASE_URL="${DATABASE_URL:-file:/app/data/prod.db}"
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 ""

# 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..."
  npx prisma migrate deploy --schema=./packages/shared/prisma/schema.prisma
else
  echo "No Prisma migrations found. Syncing schema with db push..."
  npx prisma db push --skip-generate --schema=./packages/shared/prisma/schema.prisma
fi

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