#!/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"

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

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