#!/bin/bash
set -e

cd /var/www/aigo

# Ensure storage directories exist (volume mount may hide image-created dirs)
mkdir -p storage/framework/{cache/sessions,cache/data,views,testing} \
    storage/logs \
    bootstrap/cache
chown -R www-data:www-data storage bootstrap/cache

# Wait for database
if [ -n "$DB_HOST" ]; then
    echo "Waiting for database connection..."
    for i in $(seq 1 30); do
        if php -r "
            try {
                new PDO('mysql:host=$DB_HOST;port=${DB_PORT:-3306}', '$DB_USERNAME', '$DB_PASSWORD');
                echo 'ok';
            } catch (PDOException \$e) {
                exit(1);
            }
        " 2>/dev/null; then
            echo "Database connected."
            break
        fi
        echo "Waiting for database... attempt $i"
        sleep 2
    done
fi

# Create storage symlink
php artisan storage:link --force

# Run migrations
php artisan migrate --force

# Cache
php artisan config:cache
php artisan route:cache
php artisan view:cache

exec "$@"
