#!/usr/bin/env bash
set -euo pipefail

cd /var/www/html

# If .env missing, create it from .env.testing (safe for local dev)
if [ ! -f .env ] && [ -f .env.testing ]; then
  cp .env.testing .env
  sed -i "s/DB_HOST=.*/DB_HOST=mysql/" .env || true
  sed -i "s/DB_DATABASE=.*/DB_DATABASE=building_db/" .env || true
  sed -i "s/DB_USERNAME=.*/DB_USERNAME=root/" .env || true
  sed -i "s/DB_PASSWORD=.*/DB_PASSWORD=secret/" .env || true
  sed -i "s/REDIS_HOST=.*/REDIS_HOST=redis/" .env || true
  sed -i "s|APP_URL=.*|APP_URL=http://localhost:8000|" .env || true
fi

# Install PHP deps if missing
if [ ! -f vendor/autoload.php ]; then
  echo "[container:init] running composer install"
  composer install --prefer-dist --no-interaction --no-scripts --optimize-autoloader || true
fi

# Install node deps and build assets (if present)
if [ -f package.json ] && [ ! -d node_modules ]; then
  echo "[container:init] running npm ci && npm run build"
  npm ci --no-audit --no-fund || true
  npm run build || npm run dev || true
fi

# Generate app key if not present
if [ -f .env ] && ! grep -q '^APP_KEY=' .env; then
  php artisan key:generate --force || true
fi

# Optionally run migrations & seed (controlled by APP_INIT env)
if [ "${APP_INIT:-true}" = "true" ]; then
  echo "[container:init] running migrations and seed (APP_INIT=true)"
  php artisan migrate --force || true
  php artisan db:seed --force || true
fi

# Ensure storage permissions
chown -R www-data:www-data storage bootstrap/cache || true

# Exec the main process (php-fpm)
exec "$@"
