#!/bin/sh
set -e

# Wait for the database to be reachable
until php -r "new PDO('mysql:host=${DB_HOST};port=${DB_PORT}', '${DB_USERNAME}', '${DB_PASSWORD}');" 2>/dev/null; do
  echo "Waiting for database..."
  sleep 2
done

php artisan migrate --force

# Generate the encryption key ONCE. Because .env is a mounted host file, this
# key persists across container rebuilds/restarts -- critical since it protects
# encrypted fields like Medicare numbers. Never delete the key from .env once set.
if ! grep -q "^APP_KEY=base64:" /var/www/.env 2>/dev/null; then
  echo "No APP_KEY found - generating one now (this should only happen on first run)."
  php artisan key:generate --force
fi

# Seed only on first boot (marker file survives container restarts via the storage volume)
if [ ! -f /var/www/storage/.seeded ]; then
  php artisan db:seed --force
  touch /var/www/storage/.seeded
fi

php artisan storage:link || true
php artisan config:cache
php artisan route:cache

exec "$@"
