#!/bin/sh
set -e

echo "Running database migrations..."
max_retries=30
i=0
until [ $i -ge $max_retries ]; do
  if bun run --cwd apps/backend prisma:migrate:deploy 2>&1; then
    echo "Migrations complete"
    break
  fi
  i=$((i + 1))
  echo "Migration attempt $i failed, retrying in 2s..."
  sleep 2
done

if [ $i -ge $max_retries ]; then
  echo "Failed to run migrations after $max_retries attempts"
  exit 1
fi

echo "Running database seed..."
bun run --cwd apps/backend prisma:seed && echo "Seed complete" || echo "Seed skipped or already applied"

exec "$@"
