#!/bin/sh
set -e

# ============================================================
# Docker Entrypoint — SocialAI Backend
# Runs migrations, optimizations, and starts supervisord
# ============================================================

echo "====================================================="
echo " SocialAI Platform — Backend Startup"
echo "====================================================="

# ── Wait for PostgreSQL ───────────────────────────────────────
echo "[1/6] Waiting for PostgreSQL..."
until php -r "
  \$conn = @pg_connect('host=${DB_HOST:-postgres} port=${DB_PORT:-5432} dbname=${DB_DATABASE:-socialai} user=${DB_USERNAME:-socialai} password=${DB_PASSWORD:-secret}');
  if (\$conn) { echo 'ok'; pg_close(\$conn); } else { exit(1); }
" 2>/dev/null; do
  echo "      PostgreSQL not ready, retrying in 2s..."
  sleep 2
done
echo "      PostgreSQL is ready ✓"

# ── Wait for Redis ────────────────────────────────────────────
echo "[2/6] Waiting for Redis..."
until php -r "
  \$redis = new Redis();
  try {
    \$redis->connect('${REDIS_HOST:-redis}', ${REDIS_PORT:-6379});
    \$redis->auth('${REDIS_PASSWORD:-redissecret}');
    echo 'ok';
  } catch (Exception \$e) { exit(1); }
" 2>/dev/null; do
  echo "      Redis not ready, retrying in 2s..."
  sleep 2
done
echo "      Redis is ready ✓"

# ── Create storage directories ────────────────────────────────
echo "[3/6] Creating storage directories..."
mkdir -p /var/www/html/storage/app/public
mkdir -p /var/www/html/storage/framework/cache/data
mkdir -p /var/www/html/storage/framework/sessions
mkdir -p /var/www/html/storage/framework/views
mkdir -p /var/www/html/storage/logs
mkdir -p /var/log/supervisor
mkdir -p /var/log/php-fpm
chown -R www-data:www-data /var/www/html/storage
echo "      Storage directories created ✓"

# ── Run database migrations ───────────────────────────────────
echo "[4/6] Running database migrations..."
php artisan migrate --force --no-interaction
echo "      Migrations complete ✓"

# ── Create storage symlink ────────────────────────────────────
echo "[5/6] Creating storage symlink..."
php artisan storage:link --force 2>/dev/null || true
echo "      Storage symlink created ✓"

# ── Optimize Laravel ──────────────────────────────────────────
echo "[6/6] Optimizing application..."
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan event:cache
echo "      Application optimized ✓"

echo "====================================================="
echo " Startup complete. Starting services..."
echo "====================================================="

# ── Execute the main process ──────────────────────────────────
exec "$@"