#!/bin/bash

cd /var/www/aigo

# Ensure storage directories exist
mkdir -p storage/framework/{cache/sessions,cache/data,views,testing} \
    storage/logs \
    bootstrap/cache 2>/dev/null || true
chown -R www-data:www-data storage bootstrap/cache 2>/dev/null || true

# Generate app key if missing (required by Laravel)
php artisan key:generate --force 2>/dev/null || true

# Wait for database
if [ -n "$DB_HOST" ]; then
    echo "Waiting for database connection..."
    DB_OK=
    for i in $(seq 1 15); do
        php -r "
            try {
                new PDO('mysql:host=$DB_HOST;port=${DB_PORT:-3306}', '$DB_USERNAME', '$DB_PASSWORD');
                exit(0);
            } catch (PDOException \$e) {
                exit(1);
            }
        " 2>/dev/null && DB_OK=1 && break
        echo "Waiting for database... attempt $i"
        sleep 2
    done
    if [ -n "$DB_OK" ]; then
        echo "Database connected."
        php artisan storage:link --force 2>/dev/null || true
        php artisan migrate --force 2>/dev/null || true
    else
        echo "Warning: Database not available. Skipping migrations."
    fi
fi

php artisan config:cache 2>/dev/null || true
php artisan route:cache 2>/dev/null || true
php artisan view:cache 2>/dev/null || true

exec "$@"
