#!/bin/sh

echo "🚀 Starting AI Learning Platform Backend..."

# Wait for PostgreSQL to be ready
echo "⏳ Waiting for PostgreSQL to be ready..."

# In development, prefer migrate deploy if migrations exist and flag enabled; otherwise use db push
# Accept both "1" and "true" for PRISMA_MIGRATE
if ([ "${PRISMA_MIGRATE}" = "1" ] || [ "${PRISMA_MIGRATE}" = "true" ]) && [ -d "./prisma/migrations" ] && [ "$(ls -A ./prisma/migrations 2>/dev/null)" ]; then
  echo "🗂️ Applying Prisma migrations (deploy)..."
  npx prisma migrate deploy --schema=./prisma/schema.prisma
else
  echo "🗂️ Syncing schema with db (db push)..."
  npx prisma db push --schema=./prisma/schema.prisma
fi

echo "✅ PostgreSQL is ready!"

# Generate Prisma client
echo "🔧 Generating Prisma client..."
npx prisma generate --schema=./prisma/schema.prisma

# Optional: Seed the database when requested
# Accept both "1" and "true" for RUN_SEED
if [ "${RUN_SEED}" = "1" ] || [ "${RUN_SEED}" = "true" ]; then
  echo "🌱 Seeding database with initial data..."
  npx tsx src/prisma/seed.ts
else
  echo "🌱 Skipping seeding (RUN_SEED != 1 and != true)"
fi

# Start the application (prod vs dev)
if [ "$NODE_ENV" = "production" ]; then
  echo "🚀 Starting application in production mode..."
  # Build TypeScript to dist and start Node
  npm run build
  exec npm run start
else
  echo "🎉 Starting application in development mode..."
  exec npm run dev
fi