FROM dunglas/frankenphp:1-php8.4-alpine

RUN apk add --no-cache \
    nodejs \
    npm \
    git \
    mariadb-client \
    bash \
    vim

RUN install-php-extensions \
    pdo_mysql \
    opcache \
    zip \
    gd \
    intl \
    bcmath \
    pcntl \
    xdebug

COPY --from=composer:2 /usr/bin/composer /usr/bin/composer

WORKDIR /app

RUN mv "$PHP_INI_DIR/php.ini-development" "$PHP_INI_DIR/php.ini"

RUN echo "xdebug.mode=off" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
    && echo ";xdebug.client_host=host.containers.internal" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
    && echo ";xdebug.start_with_request=yes" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini

RUN cat > /etc/caddy/Caddyfile <<'EOF'
{
    frankenphp
    order php_server before file_server
}

:8000 {
    root * /app/public

    php_server {
        index index.php
    }

    encode gzip

    file_server

    header {
        X-Frame-Options "SAMEORIGIN"
    }
}
EOF

RUN cat > /start.sh <<'EOF'
#!/bin/sh
set -e

if [ ! -f ".env" ]; then
    echo "Creating .env from .env.example..."
    cp .env.example .env
fi

if [ ! -f "vendor/autoload.php" ]; then
    echo "Installing composer dependencies..."
    composer install
fi

echo "Installing npm dependencies..."
rm -rf node_modules 2>/dev/null || true
npm install --cache /tmp/.npm

php artisan config:clear || true
php artisan cache:clear || true

if ! grep -q "^APP_KEY=base64:" .env 2>/dev/null; then
    echo "Generating application key..."
    php artisan key:generate
fi

echo "Waiting for database..."
until mariadb -h "$DB_HOST" -u "$DB_USERNAME" -p"$DB_PASSWORD" -e "SELECT 1" >/dev/null 2>&1; do
    sleep 2
done

php artisan migrate --force || echo "Migration failed or not needed"

npm run dev &

exec frankenphp run --config /etc/caddy/Caddyfile
EOF

RUN chmod +x /start.sh

EXPOSE 8000 5173

CMD ["/start.sh"]
