# ============================================================
# izibrick — Production Dockerfile (PHP-FPM + Nginx)
# Symfony 7.3 website builder platform
# ============================================================

# --- Stage 1: Composer dependencies ---
FROM composer:2 AS composer-stage
WORKDIR /app
COPY composer.json composer.lock ./
RUN composer install --no-dev --no-scripts --no-autoloader --prefer-dist
COPY . .
RUN composer dump-autoload --optimize --classmap-authoritative \
    && composer run-script post-install-cmd --no-interaction

# --- Stage 2: PHP-FPM production image ---
FROM php:8.2-fpm AS php-stage

# Install system dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
    libicu-dev \
    libzip-dev \
    libxml2-dev \
    libfreetype6-dev \
    libjpeg62-turbo-dev \
    libpng-dev \
    libonig-dev \
    supervisor \
    nginx \
    curl \
    && rm -rf /var/lib/apt/lists/*

# Install PHP extensions
RUN docker-php-ext-configure gd --with-freetype --with-jpeg \
    && docker-php-ext-install -j$(nproc) \
    intl \
    mbstring \
    pdo_mysql \
    xml \
    zip \
    opcache \
    gd

# Install APCu for caching
RUN pecl install apcu \
    && docker-php-ext-enable apcu

WORKDIR /app

# Copy PHP production config
COPY docker/php.ini /usr/local/etc/php/conf.d/99-app.ini

# Copy Nginx config
COPY docker/nginx.conf /etc/nginx/sites-available/default
RUN ln -sf /etc/nginx/sites-available/default /etc/nginx/sites-enabled/default

# Copy Supervisor config
COPY docker/supervisord.conf /etc/supervisord.conf

# Copy application from composer stage
COPY --from=composer-stage /app /app

# Set permissions
RUN chown -R www-data:www-data /app/var /app/public \
    && mkdir -p /app/var/cache /app/var/log /app/var/share \
    && chmod -R 775 /app/var

# Compile assets and warm up cache
RUN php bin/console asset:install public --env=prod \
    && php bin/console cache:warmup --env=prod

# Expose port 80 (Nginx)
EXPOSE 80

# Health check
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \
    CMD curl -f http://localhost/health || exit 1

# Supervisor starts Nginx + PHP-FPM
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisord.conf"]
