#!/bin/sh
set -e

# Wait for the database, then ensure the schema + seed defaults exist (idempotent).
# Only the web container runs schema/seed; the worker just waits for the DB.
echo "Waiting for the database..."
tries=0
until php bin/console dbal:run-sql "SELECT 1" >/dev/null 2>&1; do
  tries=$((tries + 1))
  if [ "$tries" -gt 30 ]; then
    echo "Database not reachable after 60s — continuing anyway."
    break
  fi
  sleep 2
done

if [ "${RUN_MIGRATIONS:-1}" = "1" ]; then
  echo "Ensuring database schema..."
  php bin/console doctrine:schema:update --force --complete --no-interaction || true
  echo "Seeding config-store defaults..."
  php bin/console app:seed --no-interaction || true
fi

php bin/console cache:clear --no-interaction || true

exec "$@"
